Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send data to a node script from a browser?

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?

like image 834
Nick Manning Avatar asked Apr 29 '26 11:04

Nick Manning


1 Answers

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.

like image 130
Explosion Pills Avatar answered May 02 '26 01:05

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!