1

I am trying to get data from an api in Nodejs and put it in a variable, once I get that data I would use different bits of it such as the people who are in space.

I am struggling to find out how here is my code:

const request = require("request")

let url = 'http://api.open-notify.org/astros.json';

let data = request(url, (error, response, body) => {
    let data;
    if (!error && response.statusCode == 200) {
        data = body
    }
    return data
})


console.log(data)

My output

My output

Carlos Cavero
  • 3,011
  • 5
  • 21
  • 41
  • First of all, welcome to StackOverflow. Following the advices of the community, it is recommended to include text formatted instead of images. Please check the documentation [on how to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Carlos Cavero Mar 22 '19 at 10:32
  • Looks like you've done the hard bit - your output looks like it is probably complete, but you don't give us much info on what you want to extract – MikeB Mar 22 '19 at 10:40
  • @MikeBrockington I want to extract the json data fron here: http://api.open-notify.org/astros.json –  Mar 22 '19 at 10:47
  • That is what you have in the image, isn't it? Is that not actually your output? – MikeB Mar 22 '19 at 10:48
  • @MikeBrockington — That's the request object, not the body of the response. (The question isn't made clearer by having two different variables named `data` in different scopes). – Quentin Mar 22 '19 at 11:28
  • @Quentin How do I extract the body of the response? –  Mar 22 '19 at 11:40
  • @jrmci — You already are, but you're not looking at that value. See the duplicate question. – Quentin Mar 22 '19 at 11:41
  • @Quentin I should be looking at callbacks, right? –  Mar 22 '19 at 12:04
  • `(error, response, body) => { ... }` **is** a callback – Quentin Mar 22 '19 at 12:04
  • @Quentin so what part should I be looking at? –  Mar 22 '19 at 12:05
  • @jrmci first add few logs for the response and body, you should have a property in response or in body that you can read the json data. – Harshana Mar 22 '19 at 23:30

0 Answers0