Nodejs Hapi - 如何启用跨源访问控制

Nodejs Hapi - How to enable cross origin access control

我正在使用 HapiJs Restful 网络服务并尝试启用 cors,以便来自不同域的任何客户端都可以使用我的服务。我在服务器连接对象中尝试了 cors=true 但没有用。

你把cors=true放在哪里了?你能添加一些代码吗?

不知道你把 cors = true 放在哪里了,这段代码可能对你有帮助:

server.connection({ routes: { cors: true } })

或者尝试在路由的配置部分添加允许的 cors。

server.route({
    config: {
        cors: {
            origin: ['*'],
            additionalHeaders: ['cache-control', 'x-requested-with']
        }
    },

看看这个问题:hapi.js Cors Pre-flight not returning Access-Control-Allow-Origin header

我找到了适用于 Hapi 18 的解决方法。请安装 hapi-cors 插件,设置正确的本地主机端口,然后设置插件:


const start = async function () {
  try {
    await server.register({
      plugin: require('hapi-cors'),
      options: {
        origins: ['http://localhost:4200']
      }
    });
    await server.start();
    console.log('server started');
  } catch (err) {
    console.log(err);
    process.exit(1);
  }
};

start();

除了@James111的回答,

即使那个答案不适合你。检查您发送的其他 Auth headers。

在我的例子中是 X_AUTH_TOKEN,因此在 additionalHeaders 中您可能还想添加您的自定义 header。

例如

additionalHeaders: ['cache-control', 'x-requested-with', 'X_AUTH_TOKEN']