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?

3
  • It says it's undefined. Commented Jan 22, 2016 at 16:59
  • 1
    The request object is a stream, so I think you'll need to handle the data event. Commented Jan 22, 2016 at 17:06
  • How do I do this @MinusFour? Commented Jan 22, 2016 at 17:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You're totally right... the typical express body-parser...!
Thanks a lot, you're definitely on to something. I'm still having trouble. Now I'm getting SyntaxError: Unexpected end of input. It goes away when I comment out console.log(JSON.parse(body));
@NickManning would appear that body does not have valid JSON. Try just console.log(body)
@ExplosionPills---doing that outputs [object Object].
Nevermind, sorry. I forgot that I had taken out JSON.stringify in my html file while I was trying to figure it out. Thanks @ExplosionPills and TJ Crowder.

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.