gpt4 book ai didi

javascript - 由于缺少自定义 header ,身份验证中间件会阻止 OPTIONS 预检请求

转载 作者:行者123 更新时间:2023-12-03 02:39:11 25 4
gpt4 key购买 nike

我有一个使用 axios 的 React 应用程序作为 HTTP 库,express使用 http-proxy-middleware 的服务器包和 API express包含 API 的服务器。

React 应用程序应通过代理身份验证服务器与 API 服务器通信,如下所示:

Communication between client and API server goes through proxy server

在我的 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()
})

问题是发送请求时我收到此响应:

enter image description here

我认为这是由于身份验证中间件尝试访问 x-access-token标题来自 OPTIONS请求不存在,因此返回 401。如果我删除 authentication来自代理方法的中间件然后请求通过。

如何制作x-access-token存在于 OPTIONS要求?或者说,处理这种情况的正确方法是什么?

最佳答案

在 facebook 中不允许粘贴代码,不确定为什么,所以粘贴在这里:

在您的中间件中缺少的是(对于您评论的选项部分):

if (req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}

对于错误部分,正如您所说,身份验证在 cors 部分之前触发,因此您可能必须在身份验证之前设置该代码(安全部分我不太确定)

关于javascript - 由于缺少自定义 header ,身份验证中间件会阻止 OPTIONS 预检请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48402280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com