3

On page load, I am running this javascript in a script tag:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://lvh.me:1337", true);
xhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhttp.send(JSON.stringify({hello:"goodbye"}));

Then the code for the node script is

var http = require('http');
http.createServer(function (request, response) {
    response.writeHead(200, {
        'Content-Type': 'text/plain',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
    });
    console.log(request);
    response.end("");
}).listen(1337);

But in the console.log, I don't see my {"hello":"goodbye"} object anywhere. How do I get access to this object?

Nick Manning
  • 2,828
  • 1
  • 29
  • 50

1 Answers1

5

The createServer docs tell us that the callback you provide will be triggered by the request event. The request event docs tell us that request (the first argument) is an http.IncomingMessage. This does not have a body property, but it implements ReadableStream and you can listen for the 'data' event to gather the data:

// ES2015 (all of the below is supported in current NodeJS)
let body = '';
request.on('data', chunk => body += chunk);
request.on('end', () => console.log(JSON.parse(body)));

or

// ES5
var body = '';
request.on('data', function (chunk) {
   body += chunk;
});
request.on('end', function(){
  console.log(JSON.parse(body));
});

There are a lot of http server implementations out there that will abstract this process for you and give you a request.body to work with. body-parser is a prime example and will even parse JSON for you.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405