LonelyDaoist
LonelyDaoist

Reputation: 714

Difference between app.get() and app.route().get()

What is the difference between these two statements:

app.get('/',someFunction);

app.route('/').get(someFunction);

Please note I'm not comparing router.get and app.get

Upvotes: 5

Views: 1860

Answers (1)

jfriend00
jfriend00

Reputation: 707158

Suppose you want to do three routes on the same path:

app.get('/calendarEvent', (req, res) => { ... });
app.post('/calendarEvent', (req, res) => { ... });
app.put('/calendarEvent', (req, res) => { ... });

Doing it that way requires you to duplicate the route path each time.

You could instead do this:

app.route('/calendarEvent')
  .get((req, res) => { ... })
  .post((req, res) => { ... })
  .put((req, res) => { ... });

It's basically just a bit of a shortcut if you have routes for multiple different verbs all on the same path. I've never had an occasion to use this, but apparently someone thought it would be handy.

It might be even more useful if you had some sort of common middleware that was unique to just these three routes:

app.route('/calendarEvent')
  .all((req, res, next) => { ... next(); })
  .get((req, res) => { ... })
  .post((req, res) => { ... })
  .put((req, res) => { ... });

One could also use a new router object for a similar purpose.


And, I guess I would be remiss if I didn't explain that there's no difference between just these two statements (which is part of what you asked):

app.get('/',someFunction); 
app.route('/').get(someFunction);

They do exactly the same thing. The rest of my answer is about what else you can do with the second option.

Upvotes: 6

Related Questions