Bing API Consumption

Asked

Viewed 64 times

1

I need to get the address of a Bing API image:

https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=pt-BR

This API returns me a JSON that contains this information I want, but I can’t access it:

{
  "images": [
    {
      "startdate": "20181023",
      "fullstartdate": "201810230700",
      "enddate": "20181024",
      "url": "/az/hprichbg/rb/LiquidNitrogen_ROW10236809816_1920x1080.jpg",
      "urlbase": "/az/hprichbg/rb/LiquidNitrogen_ROW10236809816",
      "copyright": "Liquid nitrogen (© Sunny/Getty Images)",
      "copyrightlink": "javascript:void(0)",
      "title": "",
      "quiz": "/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20181023_LiquidNitrogen%22&FORM=HPQUIZ",
      "wp": true,
      "hsh": "c15d9d44fef770c98a00bc8edc3c6ab6",
      "drk": 1,
      "top": 1,
      "bot": 1,
      "hs": []
    }
  ],
  "tooltips": {
    "loading": "Carregando...",
    "previous": "Imagem anterior",
    "next": "Próxima imagem",
    "walle": "Esta imagem não está disponível para ser baixada como papel de parede.",
    "walls": "Baixe esta imagem. O uso desta imagem é restrito ao papel de parede."
  }
}

Follows my code:

const data = fetch('https://www.bing.com/HPImageArchive.aspx? 
        format=js&idx=0&n=1&mkt=pt-BR', {method:'GET'})    
        .then(response => response.json())
        .then(result => console.log(result));
         const img = data.images['0'].url;

I’ve tried to take the quotes from scratch and also tried to put two quotes in it, but it didn’t work either way.

The error the console shows is as follows:

Uncaught Typeerror: Cannot read Property '0' of Undefined

1 answer

1

Try to do console.log(data) and you’ll understand the problem. data is a prop, not an object.

Change your code to:

var data;
const promise = fetch('https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=pt-BR', {method:'GET'}) 
        .then(response => response.json())
        .then(result => data = result);

const img = data.images[0].url
console.log(img)

To have a greater understanding about Precedents, here are some references within the Sopt forwarded by our colleague Pedro Gaspar:

What are javascript (promises)?

How to really learn how to use javascript promises?

  • 1

    I was going to answer that too, but you went faster! : ) I was going to quote these questions here as well: https://answall.com/q/119907/86952 and https://answall.com/q/16921/86952. If you want to add to the answer, it might be interesting.

  • I added, thanks for adding

Browser other questions tagged

You are not signed in. Login or sign up in order to post.