【发布时间】:2018-11-01 16:35:41
【问题描述】:
我已经面临这个问题好几天了。我正在尝试从我的网站 (mywebsite.com) 调用我的 API (api.mywebsite.com),它工作正常,直到我尝试传递授权标头。到那时,它不再是一个简单的请求,而是一个预检请求。
这是我的前端代码(JS):
fetch(generalInfo.url.api+"users/"+userId, {
method: 'GET',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"Authorization": "Bearer "+accessToken
},
withCredentials: true
});
虽然这是 API 后端的中间件:
//Allow the cors from every domain
module.exports = function (req, res, next){
res.setHeader('Access-Control-Allow-Origin', req.host);
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Authorization');
if(req.method === 'OPTIONS'){
return res.send(200);
}
next();
}
谁能帮帮我?
【问题讨论】:
-
选项请求在设计上不包含 auth 标头。
-
@KevinB 我不是要求他们传递 Auth 标头,而是我在问为什么它在收到响应并且一切正常后不发出新的 GET 请求。跨度>
-
因为……一切都不好。原点与允许的原点不匹配。错误消息至少应该告诉你这么多。
标签: ajax api cors cross-domain fetch