授权标头未在AJAX请求中发送

时间:2016-03-12 00:04:24

标签: jquery ajax node.js express

我在发送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请求。我会这样做并报告回来......

1 个答案:

答案 0 :(得分:1)

是的,正如我在编辑时所怀疑的那样。我只需要通过发送回CORS头来处理OPTIONS请求:

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();
});