User Tools

Site Tools



Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm

Martin Christen

View Martin Christen's profile on LinkedIn


Timeline of @MartinChristen

MartinChristen avatar

RT @snebiker: ‹3DGI 2019› - 4th International Conference on #3D #Geoinformation on 28th of Aug @FHNW with top talks on #AugmentedReality #3…
About 4 hours, 3 mins ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @VictorStinner: Basel in 4 photos: very sunny week, lot of music everywhere, amazing architecture, boat ferry pulled by a cable, people…
About 1 day, 5 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

The team of the FindSolar Code Spint @ #EuroPython at the FHNW Campus Muttenz - open source tool for solar panel cl…
About 2 days, 10 hours ago by: Martin Christen (@MartinChristen)

Node.js Tutorials - Part 0

Node.js Tutorial 2

Returning Dynamic JSON

In this tutorial we create a more dynamic JSON response and also listen to other events. The goal of this tutorial is running a Web Application which returns the following JSON response:

  "greeting": "Hello World",
  "date": "2013-06-30T13:56:14.794Z",
  "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0"

Where “date” contains the current date and “user-agent” contains the user agent of the request header. In this example we also want to add custom listeners for some http-Server events.

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

In this first part we create the server as we already did in the last tutorial.

myServer.addListener("connection", function(){
We add a listener which emitted when a new TCP stream is established.

myServer.addListener("request", function(req, res) {
  res.writeHead(200, {'Content-Type': 'application/json'});
  var myObject = {};
  myObject['greeting'] = 'Hello World';
  myObject['date'] = new Date();
  myObject['user-agent'] = req.headers['user-agent'];
  res.end(JSON.stringify(myObject, undefined, 2));

The “request” event is emitted when there is a request. Here we set the content type to application/json and create a JSON object containing a greeting, a date, and the user-agent. The JSON object is serialized using the stringify function.

myServer.listen(1234, '');

The server starts to listen at port 1234.

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