json - node.js http.request 获取json,json前面未定义

标签 json node.js httprequest undefined-behavior

我正在尝试通过 node.js 从 embed.ly 获取数据。

一切看起来都不错,但它在数据前面放置了一个“未定义”:

也许它与 setEncoding('utf8) 有关?

结果如下所示:

undefined[{ validjson }]

功能:

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

}

最佳答案

这是因为 body 最初是未定义的。当您使用 += 附加到它时,它会将其附加到字符串“undefined”。我希望这是有道理的。

解决方案:将body声明为空字符串:var body = "";

第二:我真的建议查看 Mikeal Rogers 的 request .

编辑:请求比基本的http api更容易一些。您的示例:

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

关于json - node.js http.request 获取json,json前面未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23139588/

相关文章:

ruby - 在 Ruby 中使用 HTTParty 解析 JSON API 调用

image - 很少有大图像与许多小图像

grails - 带有URL的Grails中的HTTP GET请求

android - 在android中将JsonArray转换为byte[]数组

json - 将 json 解码为结构时如何不允许空字段

c - C 中的字符串提取

java - 如何从我的 EC2/Node.js 应用程序在另一个 AWS EC2 中运行 java jar 文件?

javascript - 如何编写带有 M/D/YYYY 格式日期条件并存储为字符串的查找查询

javascript - 解析完成后如何将内容从服务传递到 Controller ?

Android Developer Console 如何发送 HTTP 请求?