我想为v17创建一个HapiJS插件,以将一些自定义标头附加到响应中,以用于cors,但这无关紧要。
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);
});
},
};
这是我到目前为止所拥有的。我认为这是对的,因为我遇到错误。
我也尝试过:
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;
});
这似乎在本地有效,但在测试过程中失败。
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)
如何在HapiJS v17中实现此目的?该版本中的API似乎已完全重构,并且在此版本的Hapi中几乎没有具体的示例。
谢谢!
答案 0 :(得分:1)
当您返回Boom错误时,您的响应行为会更改。试试这个。
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'
};