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

我遇到问题正确发送授权标头以及AJAX请求。 我读过这可能是一个CORS的问题,但我相信一切正确configuration。 以下是客户端的代码:

$.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"但是显式授权头在服务器端不存在。

有任何想法吗?

编辑 :我现在已经意识到,我必须分开处理jQuery的初始预检选项请求。 我会这样做,并报告回来…

是的,正如我在编辑中怀疑的那样。 我只需要通过发回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(); });