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

I just signed up as @europython volunteer. Still many spaces available! Do it now! https://t.co/Bam6ZJCjFR
About 1 day, 23 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

@Mr_Robinini I will do a talk about this at @EuroSciPy in August...
About 2 days, 22 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

@Mr_Robinini Try jupyterhub, you can start jupyterlab too (change config file). https://t.co/kDKr9oV946
About 2 days, 22 hours 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