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