如何在我的路由中添加中间件?

How can I add a middleware in my route?

在快递中我有这样的东西:

router.get('/foo', middlewareFunction, function (req, res) {
    res.send('YoYo');
});

hapi中间件的形式是什么?当我有这个时:

server.route({
    method: 'GET',
    path: '/foo',
    handler: function (request, reply) {
        reply('YoYo');
    }
})

您可以使用 server.ext property to register an extension function in one of the available extension points.

例如:

server.ext('onRequest', function (request, reply) {
    // do something
    return reply.continue();
});

此功能可能会有用。这完全取决于你想用中间件做什么。

路由 pre 选项允许定义这样的预处理器方法,请查看 http://hapijs.com/api#route-prerequisites

const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 80 });

const pre1 = function (request, reply) {

    return reply('Hello');
};

const pre2 = function (request, reply) {

    return reply('World');
};

const pre3 = function (request, reply) {

    return reply(request.pre.m1 + ' ' + request.pre.m2);
};

server.route({
    method: 'GET',
    path: '/',
    config: {
        pre: [
            [
                // m1 and m2 executed in parallel
                { method: pre1, assign: 'm1' },
                { method: pre2, assign: 'm2' }
            ],
            { method: pre3, assign: 'm3' },
        ],
        handler: function (request, reply) {

            return reply(request.pre.m3 + '\n');
        }
    }
});

除了@gastonmancini 的回答,如果您使用的是 v17 及更高版本,您可能还想使用:

server.ext('onRequest', (request, h) => {
    // do something
    return h.continue;
});

根据hapi docs

"Return h.continue instead of reply.continue() to continue without changing the response."

在Hapi v17及以上版本,您可以使用以下代码

const server = new Hapi.Server({
  host: settings.host,
  port: settings.port,
  routes: {cors: {origin: ['*'] } }
});

server.ext('onRequest',async (req, h)=>{
  req.firebase = 'admin'; // This adds firebase object to each req object in HAPI
  return h.continue; // This line is important
})

现在像这样在您的路由中访问 req.firebase 对象:

 {
        method: 'POST', 
        path: '/helper/admin-object', 
        options: {
            handler: async (req, h)=>{
                console.log(req.firebase); // Prints admin
                return true;
            },

        }
    },