我正在尝试通过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”,但它会打印出“未定义”。如何访问返回给我的数据?
PS。对不起,如果这是一个重复的问题,它似乎就是那种。我发现了很多与我非常接近的问题,但并没有完全回答。我也经历了Node documentation,但这更多地涉及如何提出请求,而不是如何处理它。至少从我得到的东西。
答案 0 :(得分:3)
首先必须将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);
});
});