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; console.log(reqInfo); res.writeHead(200, {'Content-type':'application/json'}); res.end(JSON.stringify(reqInfo)); }); }); server.listen(3333); 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.
http://localhost:3333/api/employee/
http://localhost:3333/api/employee/?id=12345&name=Kay
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts