转发到另一个路由处理程序而不在express中重定向

时间:2013-10-23 14:58:38

标签: node.js express

我有以下代码:

app.get('/payment', function(req, res) {
  // do lots of stuff
});

现在我要添加以下内容:

app.post('/payment', function(req, res) {
  req.myvar = 'put something here';
  // now do the same as app.get() above
});

显然我想重用代码。我尝试在post处理程序中执行next('/payment')并将其放在get处理程序之上,但没有运气,可能是因为它们是不同的VERB。

我有什么选择?

感谢。

1 个答案:

答案 0 :(得分:5)

只需将中间件升级到自己的功能,并在两个路径中使用它。

function doLotsOfStuff (req, res) {
  // do lots of stuff
}

app.get('/payment', doLotsOfStuff);

app.post('/payment', function(req, res, next) {
  req.myvar = 'put something here';
  next();
}, doLotsOfStuff);