路由中间件

中间件在路由执行之前执行,并且可以根据 URL 决定是否执行路由器。

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

router.use(function (req, res, next) {
    var weekDay = new Date().getDay();
    if (weekDay === 0) {
        res.send('Web is closed on Sundays!');
    } else {
        next();
    }
})

router.get('/', function(req, res) {
    res.send('Sunday is closed!');
});

module.exports = router;

特定的中间件也可以发送到每个路由器处理程序。

var closedOnSundays = function (req, res, next) {
    var weekDay = new Date().getDay();
    if (weekDay === 0) {
        res.send('Web is closed on Sundays!');
    } else {
        next();
    }
}

router.get('/', closedOnSundays, function(req, res) {
    res.send('Web is open');
});

router.get('/open', function(req, res) {
    res.send('Open all days of the week!');
});