a blog for those who code

Tuesday, 29 July 2014

How to receive data from the Querystring in Nodejs

In this post we will show you how to receive data from the Querystring in Nodejs. As you all know this is the easiest way to pass data to the server.

Node provides us with a module called querystring, so we don't have to manually parse the URL to get the quesrystring data.

The querystring module provides us with the following methods.

1. querystring.stringify()
2. querystring.parse()

1. querystring.stringify(obj, [seperator], [assignment])

This function will serialize your object to a query string. In this method you have to pass the object which is mandatory and then you can override the default separator ('&') and assignmnet('=') characters.

For Example,
querystring.stringify({firstName: 'A', secondName: 'B'})
will return 'firstName=A&secondName=B'

2. querystring.parse(str, [seperator], [assignment], [options])

This is the opposite of stringify, it deseialize the query string to an object. Like stringify it also has optional parameters as seperator and assignment which you can override.

Using options you can limit the number of keys which can be processed in your querystring.

For Example,
querystring.parse('firstName=A&secondName=B')
will return {firstName: 'A', secondName: 'B'}

Lets take an example,

var http = require("http");
var querystring = require("querystring");

http.createServer(function(req,res) {
   var qs = querystring.parse(req.url.split("?")[1]),
   userName = qs.firstName + " " + qs.secondName,
   html = "<!doctype html>" + "<html><head> <title>Hello " +               userName + "</title></head>" + "<body><h1>Hello, " +             userName + "</h1></body></html>";
   res.end(html);
}).listen(8080);

If you pass an URL like localhost:8080?firstName=A&secondName=B will give you an userName as A B.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment