这可能是一个重复的问题,但我无法正确执行此操作。
我已在后端启用 CORS(阅读 this )。但是,当我尝试通过 UI 服务器访问 API 服务器上的 API 时,我得到了以下信息:
预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段身份验证。
以下是我的代码的一些相关部分:
后端
// enable CORS
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();
});
前端
$.ajax({
method: 'GET',
url: ...,
headers: {
Authentication: ...
},
...
});
最佳答案
您需要明确允许该 header
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authentication");
您最好使用一些现有的 CORS 模块,因为我不确定您的实现是否 100% 正确。
我使用这个 CORS 中间件:
function (req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", YOUR_URL); // restrict it to the required domain
res.header("Access-Control-Allow-Methods", "GET,PUT,PATCH,POST,DELETE,OPTIONS");
// Set custom headers for CORS
res.header("Access-Control-Allow-Headers", YOUR_HEADER_STRING);
if (req.method === "OPTIONS") {
return res.status(200).end();
}
return next();
};
关于node.js - 无法设置标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39721901/