是否可以添加一个特定的HTTP方法的快递中间件?

我想添加一个Express中间件,必须在POST请求发生时触发(不pipe路由URL)。

我认为这样的事情应该工作:

 app.use(function (req, res, next) { if (req.method === 'POST') { console.log('Time:', Date.now()); } }); 

但是我想知道Express是否有些东西可以处理这些场景。

是。

 app.post(function (req, res, next) { 

http://expressjs.com/api.html#router.METHOD

前面的答案不仅是正确的,而且还可以将中间件添加到特定的路由,如下所示:

 var addCustomField=function(req,res,next){ // assumes bodyparser if('object'===typeof res.body){ res.body.myCustomField=true; } next(); }; app.post('/path',addCustomField,function(req,res){ // ... });