David Sullivan
David Sullivan

Reputation: 508

How to access the data returned in an HTTPS response

I'm trying to learn how to use an API through node.js. I'm using the starwars API to learn on. I am able to get a response back when using this code:

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

that looks like this:

`{"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/"}`

I want to be able to do something like console.log(body.name) and have it print out "Luke Skywalker" but it prints out "undefined" instead. How can I access the data that's returned to me?

PS. Sorry if this is a duplicate question, it seems like the kind that would be. I've found a ton of questions that come very close to mine, but not quite answer it. I've also been through the Node documentation too, but that dealt more with how to make a request, not what to do with it. At least from what I got from it.

Upvotes: 1

Views: 459

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371138

You have to JSON.parse the string into an object first.

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);
  });
});

Upvotes: 3

Related Questions