Reputation: 543
I am using AJAX POST
data to server which use Node.js code. Very briefly, two file in this test project. Here is main.html
:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', '/', true);
xhr.send('hello');
</script>
</body>
</html>
Here the server code:
const http = require('http');
http.createServer(function(req,res) {
console.log(req.body);
}).listen(3000);
Perhaps,you have known that server will console.log()
'undefined'.
So the question is why it's 'undefined'? How to get AJAX data on server?
I know other solution according to this question.
Could you help me any other way to get data conveniently?
Upvotes: 1
Views: 631
Reputation: 8467
You've created server allright, but there's two problems:
POST
, so you need to parse POST
requests correctly (not exactly solves your issue, but you need to distinguish request methods).POST
body by default, you need to tell it how it's done, by using querystring
module, for example.Combining this together:
var qs = require('querystring');
http.createServer(function(req, res) {
if (request.method == 'POST') {
var body = '';
request.on('data', function(data) {
body += data;
});
request.on('end', function() {
var post = qs.parse(body);
// Use your POST here
console.log(post);
});
}
}).listen(3000);
JSON data - cleaner solution:
You need to encode your AJAX data with JSON
, and than parse it on the server side like this:
http.createServer(function(req,res) {
if (req.method == 'POST') {
var jsonPost = '';
req.on('data', function(data) {
jsonPost += data;
});
req.on('end', function() {
var post = JSON.parse(jsonPost);
// Use your POST here
console.log(post);
});
}
}).listen(3000);
You'd be even better off using Express.js framework for that, with it's bodyParser
module.
UPDATE - How chunks are buffered:
Consider simple example - send in xhr.send()
a LARGE amount of text, that exceeds Content-Length
. Than do the following on data
event:
req.on('data', function(data) {
console.log(data);
body += data;
});
You will see something like:
<Buffer 0a 0a 4c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74 2c 20 63 6f 6e 73 65 63 74 65 74 75 72 20 61 64 69 70 69 73 63 69 ... >
<Buffer 65 74 20 71 75 61 6d 20 63 6f 6e 67 75 65 20 6c 6f 62 6f 72 74 69 73 2e 20 50 65 6c 6c 65 6e 74 65 73 71 75 65 20 74 65 6d 70 75 73 20 75 6c 6c 61 6d ... >
<Buffer 61 2e 20 56 69 76 61 6d 75 73 20 76 69 74 61 65 20 61 6e 74 65 20 6d 65 74 75 73 2e 20 4d 61 75 72 69 73 20 71 75 69 73 20 61 6c 69 71 75 65 74 20 65 ... >
That shows that the data received in chunks on data
event. Only on end
event you will get the whole data sent (if you've aggregated it before that). Node.js doesn't handle this, that's why you need third-party modules.
That is - you cannot just get req.body
of the request, as it wasn't set at all.
Upvotes: 3