I want to create a HapiJS plugin for v17 to append to the response some custom headers, for cors but shouldn't matter.
const cors = {
name: 'cors',
version: '1.0.0',
async register(server) {
logger.debug('Initiating CORS internal plugin...');
const { port } = server;
originPort = port;
server.ext('onPreResponse', async (request, h) => {
return h
.response()
.header('Access-Control-Allow-Origin', resOrigin)
.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE')
.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization')
.header('Access-Control-Allow-Credentials', 'true')
.header('Access-Control-Max-Age', 1728000);
});
},
};
Here's what I have so far. I don't think it's right as I get an error.
I've also tried:
server.ext('onPreResponse', async (request, h) => {
const { response } = request;
response.header('Access-Control-Allow-Origin', resOrigin);
response.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
response.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');
response.header('Access-Control-Allow-Credentials', 'true');
response.header('Access-Control-Max-Age', 1728000);
return h.continue;
});
This seems to work locally but fails during testing.
console.error node_modules/hapi/lib/core.js:126
Debug: internal, implementation, error
TypeError: response.header is not a function
at header (/home/node/app/src/lib/cors.js:47:22)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
How do I acheive this in HapiJS v17? The API appears to have been completely refactored in this version and there is very little examples of what specifically I'm trying to do in this version of Hapi.
Thanks!
When you return Boom errors your response behaviour changes. Try this.
exports.plugin = {
async register(server, options) {
server.ext('onPreResponse', async (request, h) => {
const {response} = request;
if (response.isBoom) {
response.output.headers['Access-Control-Allow-Credentials'] = 'true';
response.output.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE';
} else {
response.header('Access-Control-Allow-Credentials', 'true');
response.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
}
return h.continue;
});
},
name: 'cors'
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With