简体   繁体   中英

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?

For the current version of Express, you should use express.Router().route() . See the express documentation for confirmation. express.Router().route() is not depreciated.

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. Meaning: You have one API for all the METHODS, you can write that in .route().

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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