js ajax初次跨域请求
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
在JavaScript中,使用AJAX进行初次跨域请求,通常需要服务器支持CORS(Cross-Origin Resource Sharing)。以下是一个简单的示例,展示了如何使用JavaScript的XMLHttpRequest
对象发起一个跨域请求。
服务器端(例如使用Node.js和Express):
const express = require('express');
const app = express();
const port = 3000;
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // 允许任何源的跨域请求
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.get('/api/data', (req, res) => {
res.json({ message: 'Cross-origin request received!' });
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
客户端(HTML和JavaScript):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CORS Example</title>
</head>
<body>
<script>
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:3000/api/data', true);
xhr.onload = function() {
if (this.status === 200) {
console.log(this.response);
}
};
xhr.send();
</script>
</body>
</html>
在这个例子中,服务器端设置了CORS头部,允许任何源的跨域请求。客户端代码使用XMLHttpRequest
发送一个简单的GET请求。注意,出于安全考虑,实际生产环境中应该更具体地指定允许哪些源进行跨域请求,而不是使用 '*'
。
评论已关闭