AJAX sends data to Node.js server

I try to send data from AJAX to the Node.js server, but I continue to encounter the same problem, reception.

Here is the JavaScript / AJAX client 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 underlying HTTP server that you can go to http://nodejs.org/api/http.html caused ECONNREFUSED errors (even when using sudo and port 8080), so I tried using this simple code :

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

But it saves the seal res: undefined .

On the other hand, AJAX POST does not seem to cause any console errors.

So my question is if the following:

  • How can I get a simple but robust Node.js server that can receive text that was sent using an AJAX POST request?

Thank you in advance!

Edit: Testing runs 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/'); 
+4
source share
1 answer

See an example on the main page http://nodejs.org .

 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/'); 
  • Node. The .js request object does not request the body as plain text. It needs to be processed in pieces from the data event .
  • You need to complete the request using res.end to send a response to the 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); 
+3
source

Source: https://habr.com/ru/post/1445178/


All Articles