node.js http request url param path and body

Getting http request url params, pathname and body contents in node js using http, url and querystring node modules.

var http = require('http'),
	url = require('url'),
	qs = require('querystring');

var server = http.createServer(function (req, res) {
	var urlParts = url.parse(req.url, true),
		urlParams = urlParts.query, 
		urlPathname = urlParts.pathname,
		body = '',
		reqInfo = {};

	req.on('data', function (data) {
		body += data; 

	req.on('end', function () {
		reqInfo.urlPathname = urlPathname; //sample value: /api/employee
		reqInfo.urlParams = urlParams; //sample value: {"id": "12345","name": "Kay"}
		reqInfo.body = qs.parse(body); //sample value: {"firstname": "Clarkson","lastname": "Nick"}
		reqInfo.urlParts = urlParts;

		res.writeHead(200, {'Content-type':'application/json'});

console.log("Server running at http://localhost:3333");

Sample request url, for post request, a form html form is needed, or the chrome plugin postman will do.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search