Reputation:
I've seen code written both ways.
router.get(path, callback)
and
router.route(path).get(callback)
From the surrounding code they look equivalent. The docs are here:
and
where method can be get
, post
, etc.
Why are there two ways to do this? I've read the docs and they did not help so much.
Upvotes: 8
Views: 1472
Reputation: 4668
I always use router.METHOD(path, callback)
So ONE method, ONE path, handled with ONE callback.
The second method you named can have ONE path that handles multiples methods.
So you can have both a get
and a post
method on path /user
.
If you want to setup, for example, something like CRUD routes like this:
Then I would recommend you use router.METHOD(path, callback)
approach, as you want to have unique paths for each route.
Upvotes: 0
Reputation: 1296
These are just two of the methods of the router object provided by express. According to the documentation there are a total of five methods associated with the router object.
As you have specifically asked for the router.METHOD()
& router.route()
, so I will only be focussing on these two methods.
To begin with, let us take router.MEHTOD()
method first. It simply matches the incoming requests with the path provided and performs the suitable action as per the METHOD used. METHOD is one of the HTTP methods, such as get, put, post and so on.Here, the catch is that sometimes it becomes cumbersome to deal with such different naming conventions and may also lead to duplicate route naming and things just get messed up eventually when dealing with large and complex apps.
However, in the case of router.route()
method, it returns an instance of a single route(path provided) which can then be used with the http verbs. It re-uses the path provided which avoids confusion and makes the code look clean and hence less chances of errors.
Upvotes: 1
Reputation: 3576
router.METHOD(path)
router.methods() provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST
router.get(path,callback);
router.route(path)
Returns an instance of a single route which you can then use to handle HTTP methods.
Also it avoids duplicate route naming and thus typing errors.
Thus using the instance you can define all http handlers at one go. like
router.route(path).get(callback).put(callback).post(callback).delete(callback);
Upvotes: 7