title: Undefined value in the response when sending JSON object to the client- Node.js
body: <p>I am new to <code>Node.js</code> and <code>JavaScript</code> and I was hoping to get some help after searching and being unable to find a solution. </p>
  
  <p>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:</p>
  
  <pre><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.');
      }
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>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' &amp;&amp; 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);
  </code></pre>
  
  <p>It might be that I am sending the response before the actual request has ended but I am not sure. Any ideas? </p>