我正在尝试学习如何通过 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”。我怎样才能访问返回给我的数据?
附言。抱歉,如果这是一个重复的问题,那似乎就是那种问题。我发现了很多非常接近我的问题,但没有完全回答。我也经历过 Node documentation也一样,但那更多地涉及如何提出请求,而不是如何处理请求。至少从我从中得到的。
最佳答案
您必须先将字符串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);
});
});
关于javascript - 如何访问 HTTPS 响应中返回的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49595305/