跨域调用(Cross-Origin Resource Sharing, CORS)是指浏览器在执行JavaScript代码时,由于同源策略的限制,不能直接访问不同源(域名、协议或端口不同)的资源。CORS是一种机制,允许服务器声明哪些源可以通过浏览器访问其资源。
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // 允许所有源
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.sendStatus(200); // 预检请求直接返回200
} else {
next();
}
});
app.get('/data', (req, res) => {
res.json({ message: 'This is data from the server.' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
原因:服务器未正确设置CORS头部。
解决方法:确保服务器响应包含正确的Access-Control-Allow-Origin
头部。如上例所示,在Express应用中使用中间件设置这些头部。
原因:复杂请求的预检(OPTIONS请求)未得到正确处理。
解决方法:确保服务器能够正确响应OPTIONS请求,并设置相应的允许方法和头部。
原因:服务器设置的允许源列表中未包含请求源。
解决方法:调整Access-Control-Allow-Origin
头部的值,可以是具体的源地址或使用通配符*
允许所有源。
通过以上配置和处理,可以有效解决JavaScript跨域调用Web API时遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云