node express.Router().route() vs express.route()
Solution 1
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'));
})
Solution 2
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
})
Related videos on Youtube
MarcoS
I'm a sailor. I love roaming in the Mediterranean sea on any wood piece you can stick a mast and a sail on. In my spare time I do software engineering in Turin, as a full-stack developer. I start my coding ages ago with x86 assembly; then I go with C, bash, Perl, Java; Android; currently I do MEAN stack: MongoDB, Express.js, Angular.js and of course Node.js. Obviously on the shoulders of the GNU/Linux O.S..
Updated on September 14, 2022Comments
-
MarcoS over 1 year
What should I use:
express.Router().route()
or
express.route()
?
Is it true
express.Router().route()
is someway deprecated? -
MarcoS over 8 yearsThanks... One more doubt: can I use an
:optionalParameter
withexpress.Router().route()
? I can't find it in the docs... app.route() can do it, using '?' after the param name... -
jscul over 5 yearsYes it can handle that