Nodejs Hapi - How to enable cross origin access control

夙愿已清 提交于 2020-01-14 07:15:18

问题


I am working HapiJs Restful web service and trying to enable cors so any client even from different domain can consume my services. I tried cors=true in server connection object but didn't work.


回答1:


Where did you put cors=true? Could you add some code?

Without know exactly where you've put cors = true, this bit of code may help you:

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

Or try adding the allowed cors in the config section of your route.

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

Take a look at this question: hapi.js Cors Pre-flight not returning Access-Control-Allow-Origin header




回答2:


I found workaround, that works in Hapi 18. Please instal hapi-cors plugin, set correct localhost port and then setup plugin:


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();




回答3:


Addition to @James111's answer,

Even if that answer doesn't work for you. check for additional Auth headers that you are sending.

In my case it was X_AUTH_TOKEN, so in additionalHeaders you might want to add your custom header as well.

e.g.

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


来源:https://stackoverflow.com/questions/37904597/nodejs-hapi-how-to-enable-cross-origin-access-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!