简体   繁体   English

node express.Router()。route()vs express.route()

[英]node express.Router().route() vs express.route()

What should I use: 我该怎么用:

express.Router().route()

or 要么

express.route()

?

Is it true express.Router().route() is someway deprecated? 这是真的express.Router().route()有些不赞成?

For the current version of Express, you should use express.Router().route() . 对于当前版本的Express,您应该使用express.Router().route() See the express documentation for confirmation. 请参阅快速文档以进行确认。 express.Router().route() is not depreciated. express.Router().route()不折旧。

For example: 例如:

var router = express.Router();

router.param('user_id', function(req, res, next, id) {
  // sample user, would actually fetch from DB, etc...
  req.user = {
    id: id,
    name: 'TJ'
  };
  next();
});

router.route('/users/:user_id')
.all(function(req, res, next) {
  // runs for all HTTP verbs first
  // think of it as route specific middleware!
  next();
})
.get(function(req, res, next) {
  res.json(req.user);
})
.put(function(req, res, next) {
  // just an example of maybe updating the user
  req.user.name = req.params.name;
  // save user ... etc
  res.json(req.user);
})
.post(function(req, res, next) {
  next(new Error('not implemented'));
})
.delete(function(req, res, next) {
  next(new Error('not implemented'));
})

Router.route() can use for chainable routes. Router.route()可用于可链接路由。 Meaning: You have one API for all the METHODS, you can write that in .route(). 含义:您有一个API用于所有METHODS,您可以在.route()中编写它。

    var app = express.Router();
    app.route('/test')
      .get(function (req, res) {
         //code
      })
      .post(function (req, res) {
        //code
      })
      .put(function (req, res) {
        //code
      })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM