Nodejs Hapi - How to enable cross origin access co

2019-06-15 09:47发布

问题:

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