我有这个简单的代码:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
req.lectalApiData = {
Model: Email,
conditions: req.query
};
router.use(function(req,res,next){ //this is not executing
console.log('do that')
res.json({ok:'OK'});
});
});
我显然做错了,但根据文档,它说我可以使用这种语法: http://expressjs.com/guide/routing.html
我做错了什么?
也许是因为router.use
嵌套在router.get
-
所以我的问题就变成了 - 我如何为router.get
中间件内的同一路径创建更多中间件?
答案 0 :(得分:1)
Just keep adding functions to router.get('/',
, they get executed in order. Don't forget to call next
.
router.get('/', function (req, res, next) {
req.lectalApiData = {
Model: Email,
conditions: req.query
};
next(); // pass off to next middleware
}, function(req,res,next){
console.log('do that')
res.json({ok:'OK'});
});
or better:
function doThis(req, res, next) {
req.lectalApiData = {
Model: Email,
conditions: req.query
};
next(); // pass off to next middleware
}
function doThat(req, res) {
console.log('do that')
res.json({ok:'OK'});
}
router.get('/', doThis, doThat);