Ignat Ospadov Ignat Ospadov - 18 days ago 11
JSON Question

Undefined value in the response when sending JSON object to the client- Node.js

I am new to

Node.js
and
JavaScript
and I was hoping to get some help after searching and being unable to find a solution.

I am trying to send a JSON object to the Node.js server containing an array of 2 elements (longitude and latitude) using the XMLHttpRequest method. This is the Client-side JavaScript code:

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var location = [position.coords.latitude, position.coords.longitude];
console.log(location);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/locationdata', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send(location);
});
} else {
console.log('Geolocation is not supported by this browser.');
}
}


The server receives the object without any issue. However, when I try to send the object back to the client, I get an undefined value as the response. Here is the Node.js script:

var html =
fs.readFile(__dirname + '\\public\\index.html', function(err, data) {
if (err){
throw err;
}
htmlFile = data;
});

var server = http.createServer(function (request, response) {

if (request.url == "/") {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(htmlFile);
break;
};

if (request.method == 'POST' && request.url == "/locationdata") {
var postdata = '';
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function() {
var postdata = body;
console.log(postdata);
});
response.writeHead(200, {"Content-Type": "application/json"});
response.write(JSON.stringify(postdata));
}
response.end();
});

server.listen(3000);


It might be that I am sending the response before the actual request has ended but I am not sure. Any ideas?

Answer

You are not waiting for the request data before responding, which causes you to respond with nothing. Do this instead:

        if (request.method == 'POST' && request.url == "/locationdata") {
            var body = '';
            request.on('data', function (data) {
                body += data;
            });
            request.on('end', function() {
                response.writeHead(200, {"Content-Type": "application/json"});
                response.end(data);
            });
            return;
        }