【发布时间】:2016-06-27 09:30:48
【问题描述】:
我在正确发送授权标头和 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();
...
但是没办法。
当我检查来自第二个中间件的标头时,我注意到 req.headers 包含 access-control-request-headers: "accept, authorization" 但服务器端不存在显式 Authorization 标头。
有什么想法吗?
编辑:我现在意识到我必须单独处理 jQuery 的初始预检 OPTIONS 请求。我会这样做并报告...
【问题讨论】:
标签: jquery ajax node.js express