Expressjs从另一个中间件调用中间件

时间:2018-10-22 07:21:56

标签: express

routes.js

var router = require('express').Router();
router.get('/all', require('./all'));
module.exports = router;

all.js正常工作

module.exports = function(req, res, next) {
   res.send('this one work');
};

all.js无效

const start = function(req, res, next) {
  res.write('start');
  next();
}
const finish = function(req, res, next){
  res.write('finish!');
  res.end();
}

module.exports = function(req, res, next) {
   start,
   finish
};

如何使all.js正常工作。 更新:页面的完整代码

2 个答案:

答案 0 :(得分:0)

您可以将route.js更改为以下内容:

var router = require('express').Router();
var all = require('./all');
// Call your middlewares in the desired order 
router.get('/all', all.start, all.finish);
module.exports = router;

也请阅读此question and answers,以获取更多详细信息。

根据您的评论:

all.js

const start = function(req, res, next) {
  res.write('start');
  next();
}

const finish = function(req, res, next){
  res.write('finish!');
  res.end();
}

module.exports = [start, finish];

routes.js

var router = require('express').Router();
router.get('/all', require('./all'));
module.exports = router;

答案 1 :(得分:0)

尝试一下,这将为您服务

您只需要在代码中更改两个位置,否则,一切都正确。

routes.js

    var router = require('express').Router();
    var all = require('./all');
    //call both start and finish from all.js file here
    router.get('/all', all.start, all.finish);
    module.exports = router;

all.js

    const start = function (req, res, next) {
        res.write('start');
        next();
    }
    const finish = function (req, res, next) {
        res.write('finish!');
        res.end();
    }

   //export in this way 
    module.exports = {
        start,
        finish
    }