我在发送Authorization标头和AJAX请求时遇到问题。我已经读过这可能是一个CORS问题,但我相信一切都配置正确。这是客户端的代码:
$.ajax({
url: <location>,
method: "GET",
headers: {"Authorization": 'Bearer ' + token},
success: function (user) {
Cookies.set('user', user, {expires: 1});
}
});
这是服务器端的一些代码(使用Express)。 CORS中间件:
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, HEAD, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
next();
});
我的中间件检查授权标题:
app.use(function (req, res, next) {
var config, authorization;
authorization = req.get('authorization');
if (!authorization) throw new NoAuthenticationError();
...
但是nada。
当我检查第二个中间件的标头时,我注意到req.headers
包含access-control-request-headers: "accept, authorization"
,但服务器端不存在显式的Authorization标头。
有什么想法吗?
编辑:我现在意识到我必须单独处理jQuery的初始预检OPTIONS请求。我会这样做并报告回来......
答案 0 :(得分:1)
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, HEAD, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
if (req.method === 'OPTIONS') {
return res.end();
}
next();
});