Bing API Consumption

1

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

  

link

This API returns me a JSON that contains this information I want, but I can not 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."
  }
}

Follow 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 have tried to get the quotation marks from scratch and I also tried to put two quotation marks in it, but it did not work in either way.

The error that the console shows is as follows:

  

Uncaught TypeError: Can not read property '0' of undefined

    
asked by anonymous 23.10.2018 / 17:25

1 answer

1

Try to console.log(data) and you will understand the problem. data is a promise, 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 get a better understanding of promises, here are some references within the SOpt forwarded by our colleague Pedro Gaspar:

What are promises in javascript?

How do I really learn to use promises in javascript?

    
23.10.2018 / 17:42