【问题标题】:hapijs custom http status messagehapijs 自定义 http 状态消息
【发布时间】:2017-08-04 04:22:21
【问题描述】:

我需要在 hapijs 应用程序中设置自定义 HTTP 状态消息。如何做到这一点?我的代码是:

'use strict';

const Hapi = require('hapi');

const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('Hello, world!\n')
        .header('set-cookie', 'abc=123')
        .message("Hello world");
    }
});

server.start((err) => {
    if (err) {
        throw err;
    }
    console.log(`Server running at: ${server.info.uri}`);
});

当我像这样通过 curl 调用它时: curl -v http://localhost:3000/ 我看到一个自定义 http 标头 abc=123,但 http 状态消息仍然是 OK 而不是预期的 Hello world。请帮忙。 谢谢。

【问题讨论】:

    标签: javascript node.js hapijs


    【解决方案1】:

    这是一个错误,有一个开放的pull request 可以修复它。 我可以确认我能够使用 Hapi 16.5(来自 master)重现您的问题,并且在应用拉取请求后它可以正常工作。

    如果您现在需要它并且不能等待拉取请求被接受,您可以按照我采取的步骤进行测试:

    $ rm -r node_modules/hapi
    $ git clone https://github.com/hapijs/hapi.git node_modules/hapi
    

    然后编辑node_modules/hapi/.git/config,使[remote "origin"] 块如下所示:

    [remote "origin"]
    url = https://github.com/hapijs/hapi.git
    fetch = +refs/heads/*:refs/remotes/origin/*
    fetch = +refs/pull/*/head:refs/remotes/origin/pr/*
    

    (添加第三行)

    $ cd node_modules/hapi
    $ git fetch origin
    $ git checkout pr/3560
    // optional if you don't want a nested git repo in your project
    $ rm -r .git
    

    现在您的自定义状态消息应该可以工作了 :)

    【讨论】:

    • 拉取请求合并到主分支
    • 我像这样更新了我的项目依赖文件package.json"hapi": "^16.5.2",从项目文件夹中删除了node_modules,发出了npm i 命令,因此使用正确的hapijs 版本重新加载了node_modules。但我仍然得到回复:HTTP/1.1 200 OK 而不是预期的HTTP/1.1 200 Hello world
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多