是否有可能在执行当前执行之前执行另一个路由句柄?

我正在devise一个快速节点应用程序。

假设我有2个path

“/职位/:postID /更新”

“/职位/:postID /上传”

我不知道是否有可能当人们访问第二个path时,路由可以自动运行第一个path的句柄?

你可以定义你的路线

var routes = require('./routes'); app.get('/posts/:postId/update', routes.update); app.get('/posts/:postId/upload', routes.upload, routes.update); 

所以在routes.upload里面你可以做类似的事情

 route.upload = function(req, res, next) { // do whatever you need to // this will call the next function defined // in your route definition, which is update next(); }; 

您可以创build一个引用到第一个路由的句柄,并在第二个调用它:

 function updatePost(req, res) { res.send('Updated'); } app.post('/posts/:postId/update', updatePost); app.post('/posts/:postId/upload', function upload(req, res) { const upload = req.file; // this property will differ depending upon your upload middleware // some app logic updatePost(req, res); }); 

此外,你应该考虑使用express.Router从你的服务器代码中分离你的路由。