我有一个使用axios
作为HTTP库的React应用程序,express
服务器使用包含API的http-proxy-middleware
包和API express
服务器。
React应用程序应通过代理身份验证服务器与API服务器通信,如下所示:
在我的React应用程序中,我创建了这个测试方法:
testReq(){
axios.get('http://localhost:5000/applicationData/checkMe', {
withCredentials: true,
headers: {
'x-access-token': '...'
}
})
.then(response => console.log(response.status))
.catch(e => console.log(e))
}
这是我的代理方法的样子:
server.use('/applicationData', authenticate, proxy({
target: 'http://localhost:4000',
changeOrigin: false,
onProxyReq(proxyReq, req) {
// proxyReq.setHeader('x-access-identity-email', req.decodedToken.email)
},
}))
这是上面使用的authenticate
中间件函数:
module.exports = (req, res, next) => {
const token = req.headers['x-access-token']
console.log('token', token)
if (token) {
verifyToken(token, global.config.secret).then((verificationResponse) => {
const { decoded, message } = verificationResponse
if (!decoded) return res.status(401).json({ message })
req.decoded = decoded
return next()
})
.catch((err) => {
console.error(err)
res.status(500).json({ message: 'Internal error' })
})
} else return res.status(401).json({ message: 'Missing authentication token' })
}
我在API和代理服务器上启用了CORS,如下所示:
server.all('/*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000')
res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, x-access-token')
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
res.header('Access-Control-Allow-Credentials', 'true')
next()
})
问题是我在发送请求时收到此响应:
我认为这是由于身份验证中间件试图从x-access-token
请求访问OPTIONS
标头而不存在因此返回401.如果我从代理方法中删除authentication
中间件然后请求经过。
如何在x-access-token
次请求中提及OPTIONS
?或者,处理这种情况的正确方法是什么?
答案 0 :(得分:1)
在facebook中不允许粘贴代码不确定,为什么,所以粘贴在这里:
缺少中间件的(对于您评论的选项部分):
if (req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
对于错误部分,因为您说在认证之前触发了认证,因此您可能必须在认证之前设置该代码(安全部分我不太确定)
答案 1 :(得分:0)
我认为这一行:
res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, x-access-token')
应该是:
res.header('Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, x-access-token')