user2429266
user2429266

Reputation: 430

node.js http.request for json, undefined in front of the json

I'M trying to get data from embed.ly via node.js.

Everything looks ok but it puts an "undefined" in front of the data:

Maybe it has something to do with setEncoding('utf8) ?

The results looks like this:

undefined[{ validjson }]

The function:

function loadDataFromEmbedLy( params, queue ){

  try {

    var body;

    var options = {
      host: 'api.embed.ly',
      port: 80,
      path: '/1/oembed?wmode=opaque&key=key&urls='+params,
      method: 'GET',
      headers: {'user-agent': ''}
    };

    var req = http.request(options, function(res) {

      res.setEncoding('utf8');

      res.on('end', function() {

        if( typeof body != 'undefined' ){

          console.log( body );

        }


      });

      res.on('data', function ( chunk ) {

        if( typeof chunk != 'undefined' ){

          body += chunk;

        }

    });

  });

  req.on('error', function(e) {

    console.log('problem with request: ' + e.message);

  });

  req.end();

} catch(e) { console.log("error " + e); } 

}

Upvotes: 2

Views: 1358

Answers (1)

Linus Thiel
Linus Thiel

Reputation: 39261

It's because body is initially undefined. When you append to it using +=, it will append it to the string "undefined". I hope that makes sense.

Solution: declare body as the empty string: var body = "";

Second: I really recommend checking out Mikeal Rogers' request.

Edit: request is a little easier than the basic http api. Your example:

function loadDataFromEmbedLy (params) {
    var options = {
      url: 'http://api.embed.ly/1/oembed',
      qs: {
        wmode: 'opaque',
        urls: params
      },
      json: true
    };
    request(options, function (err, res, body) {
      console.log(body);
    });
}

Upvotes: 3

Related Questions