Nodejs 从 http 请求块中读取 JSON 数据 [英] Nodejs read JSON data from a http request chunk

查看:38
本文介绍了Nodejs 从 http 请求块中读取 JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jira API 来获取单张票的数据.我已经成功地向服务器设置了一个 http GET 请求,并且可以将数据显示到控制台,但是我理想情况下需要从 JSON 格式的数据中获取某些属性.

I am using Jira API's to get data on single tickets. I have successfully setup a http GET request to the server and can display the data to the console however I ideally need to get certain properties from the data which is in JSON format.

当我尝试读取属性时,我只是未定义.

When I try to read the properties I just get undefined.

var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);         // This displays the JSON
    console.log('endSTATUS: ' + chunk.id); // This shows up undefined
});    

数据采用this格式来自jira API 供参考.res 中的第一个控制台日志成功显示了该块中的所有数据.第二个是:

The data is in this format from jira API for reference. The first console log in the res successfully displays all the data from the chunk. The second one is:

endSTATUS: undefined

推荐答案

尝试在数据流完成后获取正文.像这样:

Try to get the body after the data stream finish. Like this:

        var body = '';
        response.on('data', function(d) {
            body += d;
        });
        response.on('end', function() {

            // Data reception is done, do whatever with it!
            var parsed = JSON.parse(body);
            console.log('endSTATUS: ' + parsed.id);
        });

这篇关于Nodejs 从 http 请求块中读取 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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