As you can see the moment we are trying to have more routes and more functionality we have another issue, which is that our app.js is becoming very busy. The solution is to use express router, where we can group those routes together and as far as the functionality, we can set them up as seperate controllers.

So, like we made many APIs starting with /api/people. We will group them together in a seperate file.

Common convention is make a folder named routes.

Screenshot 2022-09-01 at 2.54.45 PM.png

In routes I will make 2 files:

  1. people.js - for /api/people APIs
  2. auth.js - for /login

In people.js: Instead of setting up the app variable I will setup the router. Which means I will not do: const app = express();

Screenshot 2022-09-01 at 2.26.13 PM.png

Now, I will put all api/people in this file:

Screenshot 2022-09-01 at 2.34.37 PM.png

Screenshot 2022-09-01 at 2.31.59 PM.png

Now, our next step is to changing from app to router. Because I want the router to handle the routing. So, I will change app to router everywhere. Now, in the bottom I will export the router.

In my app.js, I will add this router in app.use():

Screenshot 2022-09-01 at 2.48.03 PM.png

Here, you can see in line number 4 I required the newly created people route and in line number 13 I am using it with base as /api/people.

Now, here we have set the base route as /api/people but in our people.js we already have our bases set in every route. So, this is a mess. Now, we can remove /api/people from people.js routes. Now, my people.js will look like:

Screenshot 2022-09-01 at 2.43.40 PM.png

Screenshot 2022-09-01 at 2.43.58 PM.png