Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

High level overview of Steps to make a MERN stack app(CRUD) - PART 2


Chapter 2 - Express Router


1) In your backend directory create a folder routes (in routes we will store various .js files    related to specific API endpoints)

2) Inside routes folder create reddit.js (or any name)- Basically this file stores all 'Relative Routes' of a specific type relative to '/..../reddit'.

3) In reddit.js import express and using it create express Router instance in router & using router we can handle specific relative route based API requests (just like we did using app in server.js) and export router using module.exports at end of this file

4) Import the particular router from respective .js file from routes folder (in backend dir.) to server.js and name it redditRouter (in this casethen pass redditRouter to global middleware app.use('/api/reddit',redditRouter) [or with any specific route as first argument].

NOTE- the middlewares we write in reddit.js like router.get('/',(req,res)=>{}). These will have relative routes which means - the route is actually '/api/reddit/' not '/'.

5) Let's now make some APIs and test/save them on POSTMAN, by attaching various middlewares to router instance in reddit.js file.

6) Add another 'global' middleware/request handler- app.use(express.json()) in server.js - We are basically doing this to make sure we can access extra data that user sends from request methods like patch,post etc in any middleware of those types in respective .js file.

NOTE- To access the user sent data in middlewares like router.post('/',(req,res)=>{}) we use req.body which we will use later on in this CRUD app.

7) Test & Save your APIs in POSTMAN.


....... to be cont. in PART 3

X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.