【问题标题】:Nodejs getting a incomplete response bodyNodejs得到一个不完整的响应体
【发布时间】:2018-10-16 17:16:23
【问题描述】:

我正在使用http 模块向 api 发送请求。所以我的响应体非常大,而且我变得不完整,并且在尝试解析为 javascript 对象时出现错误,即 json 无效。

这是我的代码。

function sendPostRequest(method, url, data, callback) {


    if (typeof  data === 'undefined') {
        data = {};
    }

    var data = querystring.stringify(data);


    var post_options = {
        host: API.Host,
        port: API.Port,
        path: API.Prefix + url,
        method: method,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Bearer ' + API_USER.token
        }
    };


    var post_req = http.request(post_options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            callback(chunk);
        });
    });

    // post the data
    post_req.write(data);
    post_req.end();
}


sendPostRequest('GET', 'user/get_accounts', data, function (res) {
        res = JSON.parse(res);
        mainWindow.webContents.send('user:account', res);
        return;
    }, true);

请帮忙解决这个问题!谢谢!

【问题讨论】:

    标签: json node.js api http


    【解决方案1】:

    如果数据很大并且以块的形式提供(不完整的 json),您可能会遇到更好的情况:

    var post_req = http.request(post_options, function (res) {
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => { rawData += chunk; });
        res.on('end', () => {
          callback(rawData);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-09-16
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2016-08-19
      • 2022-10-25
      • 1970-01-01
      相关资源
      最近更新 更多