AJAX sending data to Node.js server

2020-06-22 04:47发布

问题:

I'm trying to send data with AJAX to a Node.js server but keep bumping into the same issue, the reception.

Here is the client-side JavaScript / AJAX code :

    var objects = [
        function() { return new XMLHttpRequest() },
        function() { return new ActiveXObject("MSxml2.XMLHHTP") },
        function() { return new ActiveXObject("MSxml3.XMLHHTP") },
        function() { return new ActiveXObject("Microsoft.XMLHTTP") }
    ];
    function XHRobject() {
        var xhr = false;
        for(var i=0; i < objects.length; i++) {
            try {
                xhr = objects[i]();
            }
            catch(e) {
                continue;
            }
            break;
        }
        return xhr;
    }
    var xhr = XHRobject();
    xhr.open("POST", "127.0.0.1:8080", true);
    xhr.setRequestHeader("Content-Type", "text/csv");
    xhr.send(myText);
    console.log(myText);

For some reason the basic HTTP server you can get on http://nodejs.org/api/http.html was causing ECONNREFUSED errors (even with sudo and port 8080) so I tried with this simple code :

var http = require('http');

http.createServer(function(req, res) {
    console.log('res: ' + JSON.stringify(res.body));
}).listen(8080, null)

But it keeps printing res: undefined.

On the other hand, the AJAX POST doesn't seem to trigger any errors in the console.

So my question if the following :

  • How can I have a simple but solid node.js server that can retrieve text that was send by an AJAX POST request ?

Thank you in advance !

Edit : The testing is done on 127.0.0.1 (localhost).

EDIT2: This is the updated Node.js code :

var http = require('http');

    var http = require('http');
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end();
      req.on('data', function(data) {
        console.log(data);
      })
    }).listen(1337, '127.0.0.1');
    console.log('Server running at http://127.0.0.1:1337/');

回答1:

Look at example on http://nodejs.org home page.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
  1. Node.js request object have not request body as plain text. It need to be handled by chunks from data event.
  2. You need to end request with res.end to send response to client.

Update:

This code should work fine:

var http = require('http');
http.createServer(function (req, res) {
  var body = '';
  req.on('data', function(chunk) {
    body += chunk.toString('utf8');
  });
  req.on('end', function() {
    console.log(body);
    res.end();    
  });
}).listen(8080);