Unfamiliar Node.js express router format

Viewed 66

I'm taking a course that provides the following code:

const router = express.Router();

router
  .route('/')
  .get(getBootcamps)
  .post(createBootcamp)

The above snippet means that GET and POST for the "/" endpoint have different routes.

I've never seen formatting like this so it's strange to me.

Why wouldn't we need separate routes for .get and .post? What is going on under the hood here? How can one be ignored?

1 Answers

Actually you're right. We should separate the get and post methods into separate methods rather than chaining into the same Express router.

The example code, you've written, it is also correct. But not recommended to be followed when dealing with large projects having many lines of business logic, we would make your code look heavy and difficult to read and understand. So it's better to separate.

Ps. There is no difference in output or performance, in any case, opted. At last, it's a matter of personal preference.

Related