我想在 res.on 函数之外使用 d 变量,但它没有看到。
换句话说,我如何访问从我的 GET 请求中得到的结果。 (我想发给客户端)
目前我可以使用 process.stdout.write(d) 行记录它。在 res.on 之外的任何地方都不起作用(即使我在外面声明)。谢谢。
socket from app
p
acks: {0: ƒ}
connected: false
disconnected: true
flags: {}
ids: 1
io: p {nsps: {…}, subs: Array(3), opts: {…}, _reconnection: true, _reconnectionAttempts: Infinity, …}
json: p {io: p, nsp: "/", json: p, ids: 1, acks: {…}, …}
nsp: "/"
receiveBuffer: []
sendBuffer: [{…}]
subs: (3) [{…}, {…}, {…}]
_callbacks: {$connecting: Array(1), $connect: Array(1), $connection: Array(1)}
__proto__: Object
答案 0 :(得分:0)
您需要使用“结束”事件。在请求正文之外声明一个数据变量,并在所有数据下载后处理数据。
let data;
function processData(data) {
// process the data here
}
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
data += d;
})
res.on("end", d => {
// Now all the data is stored in the data variable
processData(data);
});
})
另一种方法是将 res 传输到可写流中,因为 res 是可读流。
res.pipe(any_writable_stream_here);
答案 1 :(得分:0)
您可以使用承诺来做到这一点:
const https = require('https')
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
const req = () => {
return new Promise((response, reject) => {
let result = https.request(options, res => {
console.log('in here');
console.log(`statusCode: ${res.statusCode}`);
let data;
res.on('data', d => {
data += d;
// process.stdout.write(d)
})
res.on('error', error => {
console.error(error);
reject(error);
})
res.on("end", d => {
response(data);
});
})
result.end();
})
}
req().then(data => { console.log(data)}).catch(console.log);