Home > other >  Axios returning undefined when trying to obtain an image link
Axios returning undefined when trying to obtain an image link

Time:10-30

So, I have this simple axios script which is supposed to get bitcoin's image using the coingecko API.

const axios = require("axios");

async function test() {
    const { data } = await axios.get(
    `https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin&order=market_cap_desc&per_page=100&page=1&sparkline=false`
    );
    console.log(data.image);
}

test();

Although, when I run it, it just returns undefined. Whenever I try to print data, it returns this: data

What am I doing wrong?

CodePudding user response:

You are getting data as an array not an object Inside data it is at 0th index.you check inside data[0] and not inside data. So answer will be data[0].image

const axios = require("axios");

async function test() {
    const { data } = await axios.get(
    `https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin&order=market_cap_desc&per_page=100&page=1&sparkline=false`
    );
    console.log(data[0].image);
}

test();
  • Related