【问题标题】:How to access the data returned in an HTTPS response如何访问 HTTPS 响应中返回的数据
【发布时间】:2018-09-10 17:27:43
【问题描述】:

我正在尝试学习如何通过 node.js 使用 API。我正在使用 starwars API 来学习。使用此代码时,我能够得到回复:

const https = require('https');
https.get('https://swapi.co/api/people/1/', (res) => {
    res.setEncoding('utf8');
    res.on('data', function (body) {
        console.log(body);
    });
});

看起来像这样:

`{"name":"Luke Skywalker","height":"172","mass":"77","hair_color":"blond","skin_color":"fair","eye_color":"blue","birth_year":"19BBY","gender":"male","homeworld":"https://swapi.co/api/planets/1/","films":["https://swapi.co/api/films/2/","https://swapi.co/api/films/6/","https://swapi.co/api/films/3/","https://swapi.co/api/films/1/","https://swapi.co/api/films/7/"],"species":["https://swapi.co/api/species/1/"],"vehicles":["https://swapi.co/api/vehicles/14/","https://swapi.co/api/vehicles/30/"],"starships":["https://swapi.co/api/starships/12/","https://swapi.co/api/starships/22/"],"created":"2014-12-09T13:50:51.644000Z","edited":"2014-12-20T21:17:56.891000Z","url":"https://swapi.co/api/people/1/"}`

我希望能够执行console.log(body.name) 之类的操作并让它打印出“Luke Skywalker”,但它会打印出“undefined”。如何访问返回给我的数据?

PS。抱歉,如果这是一个重复的问题,那似乎是那种问题。我发现了大量与我非常接近的问题,但没有完全回答。我也经历过Node documentation,但更多的是关于如何提出请求,而不是如何处理它。至少从我从中得到的。

【问题讨论】:

    标签: javascript node.js ajax rest https


    【解决方案1】:

    你必须先把JSON.parse这个字符串变成一个对象。

    const https = require('https');
    https.get('https://swapi.co/api/people/1/', (res) => {
      res.setEncoding('utf8');
      res.on('data', function(body) {
        const obj = JSON.parse(body);
        console.log(obj.name);
      });
    });
    

    【讨论】:

    • 你是圣人!
    • 我实际上认为我尝试过使用 pokemon API。我刚刚尝试了完全相同的代码,但是使用 url \"pokeapi.co/api/v2/pokemon/8" 代替了 SyntaxError: Unexpected end of JSON input 我之前一时兴起切换到了 Starwars API。这是否意味着问题已经解决了?
    • 该 url 显示不正确,因为堆栈自动嵌入它,但它确实具有正确的 https:// 头,并且它确实连接正确并返回数据,只是在我尝试解析时出错使用 JSON.parse()
    • 为我工作:jsfiddle.net/99kh7gr0 也许你的语法错误(删除“setEncoding”也许?)
    • const https = require('https'); https.get('https://pokeapi.co/api/v2/pokemon/8/', (res) => { res.on('data', function (body) { const obj = JSON.parse(body); console.log(obj.name); }); }); 给出错误 SyntaxError: Unexpected end of JSON input at JSON.parse () at IncomingMessage. (/Users/davidsullivan/Desktop/Programing/JavaScript/Node/ api-test/api-caller.js:5:24) 在 emitOne (events.js:116:13) 在 IncomingMessage.emit (events.js:211:7) 在 IncomingMessage....... (cut对于字符限制)
    猜你喜欢
    • 2016-04-25
    • 2017-11-03
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多