在使用 Facebook graph api 时,我使用 https.get 来请求 facebook 用户数据。
var optionsP = {
host: 'graph.facebook.com',
path: '/me?access_token=XXXX'
};
https.get(optionsP, function(resp) {
resp.on('data', function(d) {
console.log('ondata')
console.log(d.length)
process.stdout.write(d)
});
}).on('error', function(e) {
console.error(e);
});
但是响应数据分为两部分!第一次打印最多 1034 个字符,然后同样的回调将再次工作并打印剩余的 1347 个字符。这些部分响应的原因是什么?
最佳答案
这很正常。 resp
是一个流。它是一个 ClientResponse 对象,实现了可读流接口(interface)。以下是文档:http://nodejs.org/api/http.html#http_http_clientresponse
您可以将输出通过管道传输到接受流的地方,或者将其存储在缓冲区中,直到您收到“结束”事件。
这是一个将数据存储在内存中的 String 中的示例,直到它全部到达:
https.get(optionsP, function(resp) {
resp.setEncoding(); //Now the data is a string!
var store = "";
resp.on('data', function(d) {
store += d;
});
resp.on('end', function() {
console.log("this is all: " + store);
});
}).on('error', function(e) {
console.error(e);
});
关于node.js - https.get response ondata 回调触发多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11815621/