最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何将中间件应用于Express中的特定路由器?

IT培训 admin 7浏览 0评论

如何将中间件应用于Express中的特定路由器?

下面的代码来自.html#middleware.router。它定义了快速路由器实例上的中间件。它工作正常,但如果我定义另一个路由器,该路由器也将使用相同的中间件。我是否可以仅为特定的express.Router()实例定义中间件?

var app = express()
var router = express.Router()

// predicate the router with a check and bail out when needed
router.use(function (req, res, next) {
  if (!req.headers['x-auth']) return next('router')
  next()
})

router.get('/', function (req, res) {
  res.send('hello, user!')
})

// use the router and 401 anything falling through
app.use('/admin', router, function (req, res) {
  res.sendStatus(401)
})
回答如下:

要使用特定于路径的东西,可以使用.all()函数

router.route('/')
    .all(function (req, res, next){
        // do middleware stuff here and call next
        next();
    })
    .get(function (req, res) {
    res.send('hello, user!');
});

如何将中间件应用于Express中的特定路由器?

下面的代码来自.html#middleware.router。它定义了快速路由器实例上的中间件。它工作正常,但如果我定义另一个路由器,该路由器也将使用相同的中间件。我是否可以仅为特定的express.Router()实例定义中间件?

var app = express()
var router = express.Router()

// predicate the router with a check and bail out when needed
router.use(function (req, res, next) {
  if (!req.headers['x-auth']) return next('router')
  next()
})

router.get('/', function (req, res) {
  res.send('hello, user!')
})

// use the router and 401 anything falling through
app.use('/admin', router, function (req, res) {
  res.sendStatus(401)
})
回答如下:

要使用特定于路径的东西,可以使用.all()函数

router.route('/')
    .all(function (req, res, next){
        // do middleware stuff here and call next
        next();
    })
    .get(function (req, res) {
    res.send('hello, user!');
});
发布评论

评论列表 (0)

  1. 暂无评论