如何在变量中保存节点js https请求

时间:2018-07-08 14:53:59

标签: node.js

我正在使用用node.js编写的api(通常仅使用php中的代码),并尝试从外部源获取数据。

具体部分如下:

var https = require("https");
var token = "Secret_Token";
var request = https.get("https://example.com?token=" + token, function(response)
{ 
var body = ""; 
response.on('data', function(chunk) 
     {
     dapi.message.send('' + chunk)
     }); 
});

我尝试将数据保存到变量中,而不是将数据直接发送到api的dapi.message.send('' + chunk)

我尝试了我知道的保存方式,但是它不起作用。

GET请求在我的测试中得到以下结果,因此需要将其保存在数组中: ["Testuser_1","Testuser_2","Testuser_3","Testuser_4","Testuser_5"]

我尝试将dapi.message.send('' + chunk)部分与var myarray = chunkvar myarray = ('' + chunk)以及其他可能性交换,但是它不起作用。

1 个答案:

答案 0 :(得分:4)

由于您正在使用数据流,因此on('data')事件可能会被触发多次。因此,您需要捕获每个事件并组装收到的所有块:

var finalResponse = ''
response.on('data', function(chunk) {
  finalResponse += chunk
}); 

由于您要等待所有数据返回,因此需要等待流end事件。此事件表明将不再通过该流发送任何数据。数据流结束后,可以使用保存在dapi.message变量中的整个响应的内容来调用finalResponse函数。您会知道数据流何时结束,因为就像data事件一样,一旦没有更多数据,就会触发end事件。

response.on('end', function() {
  dapi.message.send(finalResponse)
}); 

为方便起见,我将在end事件-https://nodejs.org/api/stream.html#stream_event_end

中包括指向Stream文档的链接。