Parsing request Body in Node

Node.jsServer Side ProgrammingProgramming

Earlier in simple code example, we saw how to route a request and creating a file to input the test data.

Now, we want to save the user entered input data into text file.

How Node.js handles incoming request data

Node.js reads data in chunks means it uses streams to read data . Once node completes reading request data, we can proceed to use it for our purpose.

First read data in chunks
const requestBody = [];
req.on(‘data’, (chunks)=>{
   requestBody.push(chunks);
});

We have registred an event called ‘data’ on incoming http request. This event will keep on streaming data and pushes to requestBody const variable.

Append the whole request data
Once data is completed, we will convert the received data to string with ‘end ’ event
req.on(‘end’, ()=>{
   const parsedData = Buffer.concat(requestBody).toString();
});

We get the request parameters in key-value pairs. We will have to split it to save the value in text file.

const username = parsedData.split(‘=’)[1];

Complete App.js file with code to save user input name is shown below −

const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res)=>{
   const url = req.url;
   if(url === '/'){
      res.write('<html>');
      res.write('<head> <title> Hello TutorialsPoint </title> </head>');
      res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/>       <button type="submit">Submit</button> </body>');
      res.write('</html>');
      return res.end();
   }
   if(url === '/username' && req.method === 'POST'){
      const requestBody = [];
      req.on('data', (chunks)=>{
         requestBody.push(chunks);
      });
      req.on('end', ()=>{
         const parsedData = Buffer.concat(requestBody).toString();
         const username = parsedData.split('=')[1];
         fs.writeFileSync('username.txt', username);
      });
      //redirect
      res.statusCode=302;
      res.setHeader('Location','/');
      return res.end();
   }
   res.write('<html>');
   res.write('<head> <title> Hello TutorialsPoint </title> </head>');
   res.write(' <body> Hello </body>');
   res.write('</html>');
   res.end();
});
server.listen(3000);
Note that we wrote file write operation inside end event :
req.on('end', ()=>{
   const parsedData = Buffer.concat(requestBody).toString();
   const username = parsedData.split('=')[1];
   fs.writeFileSync('username.txt', username);
});

This is because, we want to complete the end event first to get the username before writing it file.

Now, this is the background of working with core node.js, it will be easier to process all of this parsing logic in Express.js in a simpler way.

We will cover express.js way of handling request parsing in upcoming articles.

raja
Published on 13-May-2020 11:55:21
Advertisements