我在使用 cors 和 headers 时遇到了一些问题。我有以下中间件:
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type,X-Access-Token,Authorization');
next();
之后我有另一个中间件来检查 token :
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, config.jwtKey, (err, decoded) => {
if(err) {
return res.json({success: false, errmsg: 'Wrong key'});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403)
.send({
success: false,
message: "No token provided"
});
}
但是当我记录 req.headers 时:
{ host: 'localhost:4556',
connection: 'keep-alive',
'access-control-request-method': 'POST',
origin: 'http://localhost:4200',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'access-control-request-headers': 'authorization,content-type,x-access-token',
accept: '*/*',
dnt: '1',
referer: 'http://localhost:4200/posts',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'sv,en-US;q=0.8,en;q=0.6' }
除了“access-control-request-headers”之外,我的 header 中没有“X-access-token”。这只是名字。一定是出了什么问题,但我在谷歌搜索时发现的只是使用Access-Control-Allow-Headers
。
最佳答案
您正在查看 preflight OPTIONS request 。可以由多种条件触发,其中之一是“设置非标准 header ”(例如 X-access-token
)。
在服务器响应授予其权限的 OPTIONS 请求之前,浏览器不会发出 POST 请求(带有 X-access-token
header )。
您需要从 token 检查中间件中排除 OPTIONS 请求,这样您就不会发送 403 来响应预检(这将永远不会包含 token )。
关于javascript - Cors 和 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45696388/