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 @TFConsult: Celebrating 100th birthday of #physicist #RichardFeynman: The marvellous #Feynman lectures on #physics:
About 1 week, 4 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @sergerey: Had a fantastic time giving our workshop on Spatial Data Science with PyData at @GeoPythonConf with @levijohnwolf. Looking f…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @fridex: Everything has an end even such an excellent conference #GeoPythonConf in Basel. Thanks to organizers for such an outstanding c…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

Node.js Tutorials - Part 0

Node.js Tutorial 9

Posting data with XMLHttpRequest to a node.js server

Sometimes you want to send data to a node.js server. This is very easy. Lets assume you have the following html source code which posts a text message to a node server:

<!DOCTYPE html>
<html lang="en">
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <script type="text/javascript">
      function SendData(url, data) {
         var xhr = new XMLHttpRequest();'POST', url, true);

      SendData("", "Hello World, this is data!");
Sending data to

The function SendData simply creates a XMLHttpRequest and posts the data. It assumes to have a node.js server running at localhost port 1000.

The node.js code to receive this data looks this way:

var http = require('http');
http.createServer(function (req, res) {

   if (req.method == 'POST') {
      var post_data = '';
      req.on('data', function (data) {
         post_data += data;
      req.on('end', function () {
         res.writeHead(200, {'Content-Type': 'text/plain'});

         console.log('RECEIVED THIS DATA:\n'+ post_data)

      res.writeHead(200, {'Content-Type': 'text/plain'});

}).listen(1000, '');
console.log('Server running at');

It checks if the request method is POST and then receives the data using the data-event. Using the end-event we know when the data transfer is finished. In this event we simply log the posted data to the console.

This is quite simple isn't it?

node/tutorial09.txt · Last modified: 2013/09/16 22:06 by mchristen