我正在使用Node JS和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.
以下是“网络”标签中的内容:
最佳答案
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
}
您可能还应该定义一个合格的域,而不仅仅是*通配符
关于javascript - Hapi-启用CORS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51114723/