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, 13 hours ago by: Martin Christen (@MartinChristen)
node:tutorial02

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(){
	console.log("Connection...");
});
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, '127.0.0.1');

The server starts to listen at port 1234.


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