2015-07-10 117 views
6

在表達我有這樣的事情:如何在我的路線中添加中間件?

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

哪些是高致病性禽流感中間件的形式?當我有這樣的:

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

你想在中間件中做什麼? –

回答

4

路線選項允許定義這樣的預處理方法,請看看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'); 
     } 
    } 
}); 
+0

我知道它的一個新手問題,但如果說auth失敗,如何在函數2中停止? –

7

可以使用server.ext屬性在available extension points的一個註冊的擴展功能。

例如:

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

此功能可能是有用的。這一切都取決於你想用中間件做什麼。

+0

當然,我會嘗試與'onPreHandler'事件。 –

0

除了@gastonmancini答案,如果你正在使用V17及以上,你可能想用途:

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

根據hapi docs

「返回h.continue而不是reply.continue()繼續而不更改響應。「