Node.js HTTP 请求未返回完整响应 [英] Node.js HTTP request not returning full response

查看:49
本文介绍了Node.js HTTP 请求未返回完整响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Node 的 http 模块发出一个 HTTP 请求,但是在 data 上,返回的块似乎不满足完整的请求响应.这是我的代码:

I'm making a HTTP request using Node's http module, but on data, the chunk returned doesn't seem to content the full request response. Here's my code:

var req = http.request(httpOptions, function(res) {
    res.setEncoding('utf8');
});

req.on('response', function (response) {
    response.on('data', function (chunk) {
        console.log(chunk);
        callback(null, JSON.parse(chunk));
    });
});

req.on('error', function(e) {
    callback(e);
    //callback(e.message);
});

req.end();

有没有办法在结束请求之前等待完整的输出?难道我做错了什么?谢谢!

Is there a way to wait for the full output before ending the request? Am I doing something wrong? Thanks!

推荐答案

你也应该监听 'end' 事件

you should also listen for the 'end' event

req.on('response', function (response) {

    var data = "";

    response.on('data', function (chunk) {
        console.log(chunk);
        data += chunk;
    });

    response.on('end', function(){
        callback(data);
    })

});

这篇关于Node.js HTTP 请求未返回完整响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆