我正在使用Node和Hapi (v17)编写BE应用程序。在服务器运行时,我尝试使用POST方法调用端点,但一直收到一条错误消息:
Failed to load http://localhost:8001/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我想在服务器站点上启用CORS,但对我来说什么都不起作用。
下面是我如何在服务器站点上启用CORS:
const hapi = require('hapi')
const server = hapi.server({
port: 8001,
host: 'localhost',
routes: {
cors: true
}
})我也尝试为特定路由启用cors,但这也没有效果:
server.route({
method: 'POST',
path: '/login',
config: {
cors: {
origin: ['*'],
additionalHeaders: ['cache-control', 'x-requested-with']
}
},
handler: async (request, reply) => {
return User.login(request, reply)
}
})有人知道我应该怎么做才能启用CORS并摆脱这个问题吗?
此外,还有一个来自浏览器的网络选项卡的屏幕截图:

编辑:
我已经添加了处理OPTIONS方法的路由,现在我有了另一个问题。
Failed to load http://localhost:8001/login: Request header field access-control-allow-credentials is not allowed by Access-Control-Allow-Headers in preflight response.
以下是网络选项卡中的内容:

发布于 2019-03-13 22:48:54
cors: {
origin: [
'*'
],
headers: ["Access-Control-Allow-Headers", "Access-Control-Allow-Origin","Accept", "Authorization", "Content-Type", "If-None-Match", "Accept-language"],
additionalHeaders: ["Access-Control-Allow-Headers: Origin, Content-Type, x-ms-request-id , Authorization"],
credentials: true
}您可能还应该定义一个限定域,而不仅仅是*通配符
https://stackoverflow.com/questions/51114723
复制相似问题