【问题标题】:Modify all the request made to the hapi server修改对 hapi 服务器的所有请求
【发布时间】:2018-04-04 03:50:48
【问题描述】:

我刚刚开始探索 Hapi 服务器。我想在将其保存到后端之前修改对 Hapi 服务器发出的所有请求。我遇到了“server.ext”并尝试编写以下代码:

server.ext('onRequest', function (request, reply) {
    var path = request.path;
    path = path.replace(/\str1/g, 'str2')
    request.path = path;
    return reply.continue();
});

我想更新 request.path 但是这行代码失败了:

request.path = path;

这样做的正确方法是什么?有没有更好的方法来修改对 Hapi 服务器的所有请求?

【问题讨论】:

  • 失败时是否出现错误?它到底是做什么的?

标签: javascript angularjs node.js hapijs


【解决方案1】:

你可以使用onRequest事件,请求对象有一个更新路径的方法叫setUrl。您应该使用它,而不是直接更改路径

server.ext({
  type: 'onRequest',
  method: function (request, reply) {

    // Change all requests to '/test'
    request.setUrl('/test');
    return reply.continue();
  }
});

【讨论】:

    【解决方案2】:

    我已经运行了一些测试,我无法更改“onRequest”事件中的 request.path 属性,但设法更改了“onPreHandler”。

    “onRequest”总是触发超时错误,这意味着当你尝试在“onRequest”事件中改变 request.path 时,我猜你在内部破坏了一些东西。

    这里是示例测试代码。

    const Hapi = require('hapi');
    const Lab = require('lab');
    const lab = exports.lab = Lab.script();
    const describe = lab.describe;
    const it = lab.it;
    const beforeEach = lab.beforeEach;
    const expect = require('code').expect;
    
    const plugin = (server, options, next) => {
        server.ext('onPreHandler', function (request, reply) {
            // let path = request.path;
            // // path = path.replace(/\str1/g, 'str2');
            request.path = 'xox';
            return reply.continue();
        });
    
        next();
    };
    
    plugin.attributes = {
        name: 'onRequest_test'
    };
    
    describe('Hapi server', () => {
        let server;
        beforeEach((done) => {
            server = new Hapi.Server();
            done();
        });
    
    
        it('should modify the path attribute', (done) => {
            server.connection();
            server.register({
                register: plugin
            }, (err) => {
    
                expect(err).to.not.exist();
                server.route({
                    method: 'GET',
                    path: '/',
                    handler: (request, reply) => {
                        expect(request.path).to.equal('xox');
    
                        done();
                    }
                });
    
                // call main route
                server.inject({
                    method: 'GET',
                    url: '/'
                }, () => {
                    //
                });
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      相关资源
      最近更新 更多