0

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?

2
  • You forgot to JSON-encode the data you send. The XMLHttpRequest object will not silently do that for you. Commented Nov 17, 2016 at 17:39
  • I added xhr.send(JSON.parse(JSON.stringify(location))); but I still get an undefined error in the response. Commented Nov 17, 2016 at 18:09

1 Answer 1

1

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(body);
            });
            return;
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Minor error in your code. Instead of response.end(data); it should be response.end(body); but it works. Thank you! 1 question, why is it that it only works when return; is specified before the end of the if statement ?
@IgnatOspadov It's because you have response.end(); after the if statement. end marks a response as complete and stops any additional data from being transferred. In this case, we want to wait until we get all request data (end event from request object), before calling response.end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.