next()省略了route.param中的中间件子堆栈

时间:2016-08-13 11:18:37

标签: node.js express

在下面的GET /api/users/i请求示例中,即使next()中有firstMw次呼叫,也不会执行secondMw。这是为什么?我怎么能够运行 secondMw

var apiRouter = require('express').Router();

apiRouter.param('user', function firstMw(req, res, next, param) {

  if(param === 'i'){
    return next(); //jump to next mw sub-stack
  }      

  next('route'); //continue with another matching route
}, function secondMw(req, res, next, param) {
  console.log('NO, I AM NOT HERE. NEVER');
  next();
});

apiRouter.get('/users/:user', function (req, res, next) {

    res.json({

        id: req.params.user

    });

});

app.use('/api', apiRouter);

1 个答案:

答案 0 :(得分:0)

我没有看到router.params支持中间件堆栈(将定义与 app.get 进行比较)。但是你可以使用相同路线的有序定义。

'use strict';
let express = require('express');
let app = express();
app.use(require('body-parser').urlencoded({extended: false}));

var apiRouter = express.Router();

apiRouter.param('user', function mw1(req, res, next, param) {
    console.log('MW1', param);
    if (param === 'i')
        next();
    else
        next('Error message'); // better next( new Error('Error message'));
});

apiRouter.param('user', function mw2(req, res, next, param) {
    console.log('MW2', param);
    next();
})

// If next() have params then Express calls handler error 
apiRouter.use(function (err, req, res, next) {
    console.log('Error: ', err)
    res.send(err.message || err);
});

apiRouter.get('/users/:user', function (req, res, next) {
    res.json({id: req.params.user});
});    

app.use('/api', apiRouter);

app.listen(3000, function () {
  console.log('Listening on port 3000');
});