express框架无法获取自定义header信息
在route的过滤器里统一获取令牌信息
router.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization,token, X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type", "application/json;charset=utf-8");
var Authorization = req.headers['Authorization'];//undefined
var token = req.headers['token']//undefined
}
next()
});
以下是客户端请求
$(function () {
$.ajax({
type: "get",
url: "http://localhost:8081/account/list",
dataType: "json",
ContentType: "application/json",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("token", "fsddfsd");
XMLHttpRequest.setRequestHeader("Authorization", "fdfdds");
}
});
});
同样的客户端,用.NET试过能获取到自定义的信息,然而用node.js则是undefined,为何??
3 回复
加下面这行试试。 res.setHeader(“Access-Control-Expose-Headers”, “Authorization, token”);
Node 会把所有的 header keys 变成小写。所以用小写就能得到。
解决了,原因是在正式请求前会有一次获取跨域请求是否允许的访问,加一句if (req.method != “OPTIONS”) 就可以了