json的node.js http.request,未定义在json前面

我试图通过node.js从embed.ly获取数据。

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

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

结果如下所示:

undefined[{ validjson }] 

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

这是因为body最初是不确定的。 当使用+=追加到它时,它会将其追加到string“undefined”。 我希望这是有道理的。

解决scheme:将body声明为空string: var body = "";

第二:我真的build议检查Mikeal Rogers的请求 。

编辑:请求比基本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); }); } 
Interesting Posts