gpt4 book ai didi

ecmascript-6 - hapijs v17 在插件中发送响应之前设置 header

转载 作者:行者123 更新时间:2023-12-04 00:27:55 44 4
gpt4 key购买 nike

我想为 v17 创建一个 HapiJS 插件,以将一些自定义 header 附加到响应中,用于 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 中具体尝试做什么。

谢谢!

最佳答案

当您返回 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'
};

关于ecmascript-6 - hapijs v17 在插件中发送响应之前设置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54879150/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com