当 API 请求返回 CORS(跨域资源共享)错误时,可以通过以下方法解决:
const express = require('express');
const app = express();
// 添加允许跨域访问的配置
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// 处理 API 请求
app.get('/api/data', function(req, res) {
// 返回数据
res.json({ message: 'API response' });
});
// 启动服务器
app.listen(3000, function() {
console.log('Server started on port 3000');
});
module.exports = {
// ...
devServer: {
proxy: {
'/api': {
target: 'http://backend-api.example.com', // 后端 API 地址
changeOrigin: true, // 允许改变请求的源
pathRewrite: {
'^/api': '', // 去掉 API 路径中的 '/api' 前缀
},
},
},
},
};
function handleResponse(data) {
// 处理返回的数据
console.log(data);
}
const script = document.createElement('script');
script.src = 'http://backend-api.example.com/api/data?callback=handleResponse';
document.body.appendChild(script);
请根据具体情况选择适合的解决方法。