What is the difference between app.get() and app.route().get().route

In the Basic Node and Express challenges we learned to create routes with this syntax:

app.get("/", (req, res) => {
 // code
 });
});

But in the Advanced Node and Express challenges they started using this syntax:

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

What exactly is the difference between these to styles of creating routes.

Hello! Welcome to the community :partying_face:!

In the cases you expose, there’s no major difference other than the possibility of declaring the route once, and then adding the methods:

app.route('/route/one')
.get((req, res) => {
  // Do something for GET requests
})
.post((req, res) => {
  // Do something for POST requests
})
.put((req, res) => {
  // Etc.
});

This is a way of grouping the routes and their operations.

The Express.Router (app.route) allows you to make your app modular, having a small subset of the functions provided by the main app (app = express()).

As stated on the documentation of express:

A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions.

3 Likes

Thank you for your answer!

1 Like