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

@PostFinance If you are interested in Python - the @EuroPython conference, largest Python conf in Europe with over…
About 2 days, 23 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @opengeospatial: OGC seeks public comment on update to GeoTIFF standard. This minor revision to GeoTIFF enables the use of newer coordin…
About 5 days, 12 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @europython: Early-bird tickets sold out in less than 10 minutes. Amazing ! Sales were so fast, we ended up selling 275 tickets instead…
About 6 days, 15 hours 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