Getting POST Parameters in Node.js

nodejs
Published on October 18, 2018

2 Ways for Sending POST Data

HTTP allows 2 ways of sending POST data to server :

  1. Content-Type - application/x-www-form-urlencoded

    In this the POST data is send as a long query string (just like GET parameters in a url). The query string consists of name-value pairs separated by a & character. Data is url encoded.

    The above image shows application/x-www-form-urlencoded POST data, with 3 POST parameters.

  2. Content-Type - multipart/form-data

    In this POST data is send as chunks, where each POST parameter is separated by a specific boundary. This is mostly used to upload files.

    The above image shows the same POST request as above, except that the content-type is multipart/form-data.

This tutorial shows only the case of application/x-www-form-urlencoded POST request.

To get POST parameters in a multipart/form-data POST, you need to install an external module such as Multer or Formidable.

querystring Module to Read POST Data

querystring is Node.js inbuilt module that has methods to read a query string. The parse method reads the query string and returns a Javascript object.

const http = require('http'),
    querystring = require('querystring');

const server = http.createServer((request, response) => {
    if(request.method === 'POST' && request.url === '/form-submit') {
        let body = '';
        
        // very important to handle errors
        request.on('error', (err) => {
            if(err) {
                response.writeHead(500, {'Content-Type': 'text/html'});
                response.write('An error occurred');
                response.end();
            }
        });
        
        // read chunks of POST data
        request.on('data', chunk => {
            body += chunk.toString();
        });

        // when complete POST data is received
        request.on('end', () => {
            // use parse() method
            body = querystring.parse(body);
            
            // { name: 'John', gender: 'MALE', email: 'john@gmail.com' }
            console.log(body);

            // rest of the code
        });
    }
    
    // rest of the code
});

server.listen(3000);
In this Tutorial