Get the image of a Json

Asked

Viewed 646 times

3

Good morning! I’m new in javascript and I’m trying to put the image of a JSON of Bing site and put in my body but I’m not getting returns the following error:

Failed to load access-control-allow-origin: https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=pt-BR: Cross origin requests are only supported for Protocol schemes: http, data, Chrome, Chrome-Extension, https. (Anonymous) @test.html:30 test.html:35 connection error

It’s the first time that consumption api can help me please ? To get only the image I need to create a developer key ? follows my code:

function getData(url) { 
    return new Promise(function(resolve, reject){ 
      const req = new XMLHttpRequest() 

      req.open('GET', url) 
      req.onload = function () {

        if (req.status === 200) { 
          resolve(req.response)
        } else {
          reject(req.status, req.statusText) 
        }
      }
      req.onerror = function () { 
        reject("erro de conexão")

      }

       req.send() 
     })
  }

  const catchImage = document.getElementById("body") 

  getData 

  const url = getData("Access-Control-Allow-Origin: https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=pt-BR").then(function(response)
  {
    const jsonResponse =JSON.parse(response.images.url)
    console.log(response)
    catchImage.innerHTML = ""
    for (const url of jsonResponse["url"]) {
        catchImage.innerHTML = catchImage.innerHTML + "<img src='" + images.url +  "' />"
      console.log(url)
    }
  }, function(error) { console.log(error)}) 

1 answer

0

You can use one of the extensions for Chrome (for development):

Allow-Control-Allow-Origin: *

CORS Toggle

These extensions disable Chrome security with respect to communication from different hosts without the authorization setting in the header (as done by the header function() ).

Your example has no external access, that is, your API-consuming front end must be on the same host (IP + port) as the API, but the API will not work.

Browser other questions tagged

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