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

On my way to the 3D city model workshop in Bonn where I‘m presenting our latest @igeoFHNW #AugmentedReality App… https://t.co/8ghq4GfZW5
About 5 days, 6 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Teaching #Python to 11-13-year-old girls was great fun today at the Swiss national future day (#zukunftstag).… https://t.co/1lDmWdl02D
About 1 week, 2 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @GeoPythonConf: Interested in joining GeoPython 2019? Register to the mailing list: https://t.co/ub3CU7L5WL #python #GeoPython #geospat…
About 2 weeks, 2 days ago by: Martin Christen (@MartinChristen)
node:tutorial09

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">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <script type="text/javascript">
      function SendData(url, data) {
         var xhr = new XMLHttpRequest();
         xhr.open('POST', url, true);
         xhr.send(data);
      }

      SendData("http://127.0.0.1:1000/", "Hello World, this is data!");
   </script>
   <title></title>
</head>
<body>
Sending data to http://127.0.0.1:1000/
</body>
</html>

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'});
         res.end('\n');

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

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

}).listen(1000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1000/');

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