0

I'm fumbling my way through node.js with massive help from people on here and I'm struggling getting the body of a GET request into a variable.

Here's the code so far:

var speechOutput;

var myCallback = function(data) {
  console.log('got data: '+data);
  speechOutput = data;
};


var usingItNow = function(callback) {
  var http = require('http');    
  var url = 'http://services.groupkt.com/country/get/iso2code/IN';

    var req = http.get(url, (res) => {
        var body = "";

        res.on("data", (chunk) => {
            body += chunk;
        });

        res.on("end", () => {
            var result = JSON.parse(body);

            callback(result);
        });
    }).on('error', function(e){
      console.log("Got an error: ", e);
    });
};

usingItNow(myCallback);

I'm using examples from other posts to try and get the body of the GET request into the speechOutput variable but it is coming out as undefined.

Ultimately I want the RestResponse.result.name in speechOutput, but I thought I would take this one step at a time. Can anyone offer any pointers?

Further to this, I have tried the following, which still came back undefined - maybe there is a bigger issue with the code? It doesn't even seem to be getting to the parse.

res.on("end", () => {
           // var result = JSON.parse(body);        
            callback('result');
        });

putting the line callback('result'); before the line var req = http.get(url, (res) => { returns 'result' but anything else is either undefined or causes an error.

ls_dev
  • 191
  • 1
  • 14
  • I think you are confusing the (non-existent) body of the GET request with the body of the response. – Quentin Oct 25 '17 at 16:26
  • You've established that the `result` variable holds the value `undefined` … but you haven't dug back to find out why. Look at the value of `body`. – Quentin Oct 25 '17 at 16:29
  • When I run that code, the output I get is `got data: [object Object]`. There's no error. There's no sign of `undefined`. I can't reproduce the problem you describe. – Quentin Oct 25 '17 at 16:30

1 Answers1

0

Quoting Roy T. Fielding:

Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics.

Don't use get request to send body parameters. Use post requests. If you want to send data within a get request, add them to the query string.

Read this for more info about bodies in get requests: HTTP GET with request body

Update:

Try to log errors in the response, add this before you set up the listeners:

  var body = "";
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;
  if (statusCode !== 200) {
    error = new Error('Request Failed.\n' +
                      `Status Code: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('Invalid content-type.\n' +
                      `Expected application/json but received ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // consume response data to free up memory
    res.resume();
    return;
  }
 res.on("data", (chunk) => {
        body += chunk;
    });