User Tools

Site Tools


Sidebar

General

Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm


Martin Christen

View Martin Christen's profile on LinkedIn


Twitter

Timeline of @MartinChristen

MartinChristen avatar

RT @snebiker: #PlayGameLieschtel - brilliant event by Kantonsbibliothek Baselland #KBL to get kids into libraries, including family #gamede…
About 2 days, 14 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Only a handful tickets left for @PyConDE in Karlsruhe (October 24-28, 2018) - The schedule is now available at… https://t.co/Og4fp3DsoA
About 5 days, 7 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

IAMCP & @swissmade_sw Augmented Reality event just started https://t.co/bdREI6lJM4 #ar #AugmentedReality #Basel… https://t.co/9KpsdU3fvM
About 6 days, 12 hours ago by: Martin Christen (@MartinChristen)
node:tutorial03

Node.js Tutorials - Part 0

Node.js Tutorial 3

Handling Request Parameters

In this tutoroal we want to parse request parameters. For example if you request http://localhost:1234/mypath/?a=2&b=5&c=Hello we want to know the values of the result and return it in a JSON String which would look like:

{
  "path": "/mypath/",
  "query": {
    "a": "2",
    "b": "5",
    "c": "Hello"
  }
}

This can be implemented using the “URL” module which is included in the standard node.js installation.

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

The http and url modules are stored in the variables “http” and “url”.

var myServer = http.createServer(function (){});

myServer.addListener("request", function(req, res) {
  res.writeHead(200, {'Content-Type': 'application/json'});
  
  var url_parsed = url.parse(req.url, true);
  
  var myObject = {};
  myObject['path'] = url_parsed.pathname;
  myObject['query'] = url_parsed.query;
  res.end(JSON.stringify(myObject, undefined, 2));
});

myServer.listen(1234, '127.0.0.1');

using url.parse the url is parsed and stored in a parsed url object.

The parsed url object contains the “pathname” and the “query”. It also contains other fields like port, host, hash…

One more thing, if you want to run your script as a daemon, you can use “forever”, available at: http://blog.nodejitsu.com/keep-a-nodejs-server-up-with-forever


node/tutorial03.txt · Last modified: 2013/09/16 22:05 by mchristen