4

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 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

10 Comments

I don't want to send anything back, just receive what the client (AJAX) did send. The AJAX isn't a GET request but a POST.
Request must be completed in all cases. Client will waits for request end. If you don't need to send data back, just complete request with res.end(); without parameters.
Ok, so I tested your updated code, but it's still printing undefined. My node.js version is v0.8.2 if that has any importance at all.
Sorry, my fail. Node.js request have no plain request body by default. It need to be handled by chunks from data event. Check update now.
In your client code, change content type from text/csv to application/x-www-form-urlencoded. Add http:// before 127.0.0.1:8080
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.