hapi在发送响应之前设置标头

Car*_*Bda 8 javascript header handler node.js hapijs

在hapi处理程序中,我尝试在发送回视图之前在代码中设置我的响应的标头.

reply().header('cache-control', 'no-cache');

{....}

reply.view('myView', myContext);
Run Code Online (Sandbox Code Playgroud)

你我必须使用这种hold方法吗?在这种情况下,如何在渲染视图时重用响应?

谢谢你的帮助.

Rom*_*rov 7


目前在hapi 6.6.0中测试的每个响应上设置标题

server.ext('onPreResponse', function(request, reply) {

 request.response.header('X-API-VERSION', '0.0.1');

 reply();

});
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以使用hold方法,如下所示

reply.hold();
reply.view('your-view');
Run Code Online (Sandbox Code Playgroud)

甚至

reply.view('your-view').hold();
reply.send();
Run Code Online (Sandbox Code Playgroud)

回复一直持续到你调用.send()方法为止,因此:

reply().header('cache-control', 'no-cache').hold();
...
reply().send();
Run Code Online (Sandbox Code Playgroud)

可能就是你要找的东西.


Mis*_*our 6

/**************** 自 HAPI V.17 以来的重大变化 ****************/

自 hapi v.17 以来的重大变化真正的重大变化是大多数代码和库以及 api 发生了变化,并且上一个样板或指南无济于事。所以你需要寻找标记为 hapi v.17 的新文章

api 页面:https : //hapijs.com/api#response-toolkit

Firstreply()无效,您应该使用reply.response()

第二个在新指南中,reply随着h它的参数改变,所以可以命名任何东西,但正如指南所使用的h那样,你也可以使用 h 。

第三,hold()没有定义好,不需要。

第四,send()我认为不需要甚至没有定义。

以及其他一些变化。请检查上面的api链接。

所以这是我写的代码的一部分,应该提供一些很好的信息。不关心整个函数只看 h 和响应部分

static _json_response(res, request = null, h = null){
        let ret = '';
        ret = JSON.stringify(res);
        if (request == null || h == null){
                return ret;
        }else{
                const response = h.response(ret)
                        .header('cache-control', 'no-cache')
                        .type('application/json')
                return response;
        }
}
Run Code Online (Sandbox Code Playgroud)


doo*_*nch 0

你应该能够使用

var response = request.view('myView', myContext).header('cache-control: no-cache').hold();

// other stuff

response.send();
Run Code Online (Sandbox Code Playgroud)