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/');