Nodejs Hapi - How to Enable Cross-Orig Access Control

I work in a HapiJs Restful web service and try to enable cors, so any client even from different domains can use my services. I tried cors = true in the server connection object, but did not work.

+12
javascript hapijs
source share
3 answers

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

I don’t know exactly where you put cors = true , this bit of code can help you:

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

Or try adding the allowed courts in the configuration 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 does not return Access-Control-Allow-Origin header

+24
source share

I found a workaround that works in Hapi 18. Please install the hapi-cors plugin, install the correct localhost port and then install the 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(); 
0
source share

Addition to @ James111 answer,

Even if this answer does not work for you. check for additional authentication headers that you send.

In my case, it was X_AUTH_TOKEN , so in additionalHeaders you can also add your custom header.

eg

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

All Articles