Skip to content
Advertisement

How to separate CRUD routes on Node.js and Express?

when you want to have all CRUD operations of your model in one file it’s done in such a way as our 1st method:

routes.js

JavaScript

users.js

JavaScript



BUT what if we want to want to have separate files for CRUD in this form as a 2nd method ?
users
|__patchUser.js
|__deleteUser.js
|__index.js

I expect the index file to be similar to :
index.js

JavaScript

other separated files like this:
patchUser.js

JavaScript

but this doesn’t work.

How to correct the 2nd method to have separated CRUD routing files?

Advertisement

Answer

You should follow this architecture. In index.js file you should only call routes. like, userRoutes, productRoutes.

index.js

JavaScript

In routes Folder
user.js

JavaScript

In controllers folder
user folder

PatchUser.js

JavaScript

DeleteUser.js

JavaScript

For easy, you should follow following steps:

  1. Create PatchUser.js file in controllers/user/.
  2. Create userRoutes.js file in routes.
  3. Modify index.js file.
  4. Create DeleteUser.js file in controllers/user/.
  5. Modify userRoutes.js file
  6. Modify index.js file

At first,you may find this difficult but with time and practice you will find it very easy and it is the first step for clean architecture.

I hope you were looking for same.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement