【发布时间】: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