문제

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); } 

}
도움이 되었습니까?

해결책

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);
    });
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top