How to handle JSON/form data from the body of the URL in node.JS and express.
Published in
3 min readMay 26, 2021
1) Handle data inside the body of the request object using “node.JS”: — —
- First, we have to create a server using node.JS . for this refer link:- “click here to learn how to create a server using node.JS”.
- Once the server is created, now we have to create a new variable named “data” to store incoming data from the body of the request object.
- As we know request is also a eventEmitter so here we can use its req.on() method.
- req.on() also have two methods 1)data 2)end .
1) “data” will be called when data starts coming in small chunks and executes repeatedly until data stops coming.
2) “end” will be called when data stops coming.
- In the “data” method we have to store it inside the data variable for further use.
case1) Incoming data in the body of the URL is of the JSON format.
- Now, we have to handle “POST” request on route “/json” which have incoming data inside the body of format JSON.
- We can write condition as shown in the image below:-
- Here we know res.end() accepts only string data or buffer data, and incoming data is of a format string that's why we can pass it directly to the res.end().
case 2) Incoming data in the body of the URL is of the “form/urlencoded” format.
- Now, we have to handle “POST” request on route “/form” which have incoming data inside the body of format urlencoded/form.
- We can write condition as shown in the image below:-
- Here, incoming data is of format “urlencoded/form” data so first we have to convert it into object form using fs module and its “fs.parse()” method.
- After parsing it, it is stored inside the “ dataObj” variable.
- Now, we can do anything on data inside the “dataObj” object.
- If we have to send it as a response, then we have to use the “JSON.stringify()” method on the object to convert it into the stringified format.
- Now, we can pass this data to “ res.end() ” method.
2) Handle data inside the body of the request object using “expressJS”: — —
- First, we have to create a server using express. for this refer my blog link is:- “ click here to learn how to create a server using express ”.
- Now, we have to install the npm package “ morgan ” for logging the information about requests. command:- “ npm i morgan - -save ”.
- Now, we can use morgan as a first middleware which will execute every time when requests are made.
- Now, to add data inside the body of the URL is needed to be converted into an object and also needed to be added into “ req.body ” .
- Express allows us to do all the above steps using following methods:-
i) “ app.use(express.json()) ”.
ii) “ app.use(express.urlencoded()) ”.
- The code mentioned above will convert data inside the body of the URL to the object format and add it to “req.body”.
- Now we can access the object using “ req.body ” inside routing middlewares.