Pat*_*ski 5 javascript web-services node.js cors hapijs
我正在使用 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
}
})
Run Code Online (Sandbox Code Playgroud)
我也试图为特定路线启用 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)
}
})
Run Code Online (Sandbox Code Playgroud)
有谁知道我应该怎么做才能启用 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
}
Run Code Online (Sandbox Code Playgroud)
您还应该定义一个合格的域,而不仅仅是 * 通配符
| 归档时间: |
|
| 查看次数: |
2418 次 |
| 最近记录: |