Hapi-启用CORS

时间:2018-06-30 12:01:11

标签: javascript node.js web-services 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
    } 
})

我也在尝试为特定的路线启用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并摆脱问题吗?

此外,浏览器的“网络”标签中还有一个屏幕截图:

enter image description here

编辑:

我添加了处理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.

这是“网络”标签中的内容:

enter image description here

1 个答案:

答案 0 :(得分:0)

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
        }

您还应该定义一个合格的域,而不仅仅是*通配符