Dot Net For All

Parsing the Query String, HTTP Method, request Path and payload for NodeJS

Hello Friends, In my previous article I discussed about the NodeJS basics and setting up a simple and easy NodeJS server on local system. But we don’t want to stop at just creating a simple server and keep looking at the console wondering where to go from here. In this article, I will move a bit further and demo how we can get the requested URL, parsing the headers, parsing the HTTP method and parsing the request payload for NodeJS or request body transferred with the server request.

This is the Third article in the series for NodeJS free article on this blog:

  1. Writing my first Hello World program in Node JS
  2. Simple Trick to create a NodeJS Server on Windows/Ubuntu
  3. Parsing the Query String, HTTP Method, request Path and payload for NodeJS

First of all we will start where we left in the previous article. We successfully create a server and kept it listening on the port 3000.

I have modified the code from the previous article to add some more additions. This in turn will help us to understand the url and querystring modules with examples.

Lets have a look at the NodeJS code and I will discuss the code later.

var http = require('http');
var url = require('url');

var server = http.createServer(function(req, res){
    var method =  req.method.toLowerCase();
	
	//Parse the URL
	var u = url.parse(req.url,true);
	
	// Get the path
	var p = u.pathname;
	var tp = p.replace(/^\/+|\/+$/g, '');

	// Get the HTTP method
	var method = req.method.toLowerCase();

    res.end('Hello World');
	
	console.log('The reqested URL path is: ' + tp + ' and  the method is: ' + method);
});
server.listen(3000, function(){ console.log("The server is listening on port 3000")});

In the above code I have added the reference to the ‘url’ module in the beginning.

And I am using the url module to parse the requested url using the Parse method. The reason I am passing the second parameter as true to get the querystring object as the output. The ‘u’variable above contains whole bunch of keys of the parsed url and metadata that comes in with the request variable.

Lets start the server by browsing to the folder location of the server.js file.

Run the sever as mentioned in my previous article.

Open the postman client in your system and browse to ‘http://localhost:3000/test’ with GET http request as shown in the below figure.

Once you browse to the URL you can see the output in the console as shown in the below figure. This is the same console which we used to create a server.

How to get the Header Values?

The header values for the request are part of the reg object we get as parameter in the method.

Please have a look at the below code:

var http = require('http');
var url = require('url');

var server = http.createServer(function(req, res){
  	
	var headers = req.headers;

    res.end('Hello World');
	
	console.log('The headers are: ',  headers);
});
server.listen(3000, function(){ console.log("The server is listening on port 3000")});


Now create a rest in the postman client with some header values as shown in the below figure.

And lets see the output in the console.

And If you explicitly want to get some property from the header object you can change the code as shown below.

var http = require('http');
var url = require('url');

var server = http.createServer(function(req, res){
  	
	var headers = req.headers;

    res.end('Hello World');
	
	console.log('The headers are: ',  headers.header);
});
server.listen(3000, function(){ console.log("The server is listening on port 3000")});


Finally the result at the server side would be

How To receive the Request Body or Payload for NodeJS on the Server

Now suppose you are passing any request body or payload with post request And you want to receive the payload on the server.

Below code can help you to achieve the same.

var http = require('http');
var url = require('url');
var StringDecoder = require('string_decoder').StringDecoder;

var server = http.createServer(function(req, res){ 	
	

    // Get the payload,if any
    var decoder = new StringDecoder('utf-8');
    var buffer = '';
    req.on('data', function(data) {
       buffer += decoder.write(data);
    });
    req.on('end', function() {
      buffer += decoder.end();

      // Send the response
      res.end('Hello World!\n');

      // Log the request/response
      console.log('Payload received: ',buffer);
  });
    console.log('The headers are: ',  headers.header);
});
server.listen(3000, function(){ console.log("The server is listening on port 3000")});

In the above code we are decoding the payload using ‘string_decoder’ module of the NodeJS. And we are decoding the payload on the data event of the request object. Since the request body or payload would not be received by the server in one go, we have keep adding to the buffer as we receive the data.

And once the data is completely received, we can see the request payload on the request end event.

I have moved the response sending part to the end event. But you would be thinking if the request end will be called every time. And the answer is yes. But the ‘Data’ event would not be called if we do not send the request payload to the NodeJS server.

Let send some request data with the POST method in the postman client as shown in the figure below:

And we will get the result as shown in the figure below.

Conclusion:

In this article from the series to learn about the NodeJS programming we learnt about some more internal workings of the server. This can be very helpful if we want to proceed with writing come real applications using the NodeJS server.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview