首页 > 解决方案 > 用于从 api 获取 json 数据的 url 格式

问题描述

我不熟悉使用 apis 和各种获取数据的方法。我一直在关注一些教程,包括这个关于 fetch 方法或 XMLHttpRequest 方法来获取数据的教程,并且可以仅使用教程中使用的 api 来做到这一点。我希望使用这个 api但遇到了麻烦,我认为只有 url 的形式。我收到此错误:

“ CORS 策略已阻止从源“ http://localhost:8888 ”获取“ http://collections.anmm.gov.au/collections ”的访问权限:没有“访问控制允许源”“< /p>

我曾尝试使用“https”来避免 CORS 错误,但随后出现此错误:

净::ERR_CONNECTION_REFUSED。

如果我将这个 url 直接传递到浏览器中,我可以返回 json:http ://collections.anmm.gov.au/collections/json 。

我想知道的是我只是对我正在尝试的 url 有问题,或者 api 本身是否存在阻止我访问数据的问题。

在此先感谢您的任何指点。

这是我的 JavaScript 代码:

function createNode(element){
  return document.createElement(element);
}

function addClass(cls, el){
  return el.classList.add("cls");

}

function append(parent, el){
  return parent.appendChild(el);
}

const div = document.getElementById('root');
div.setAttribute('class', 'container');

//const url = 'https://randomuser.me/api/?results=100';
//can return data from this url

const url ='http://collections.anmm.gov.au/collections' // returns data if pasted directly into the browser
//const url = 'http://collections.anmm.gov.au/collections/json' // this is the format suggested in the api documentation I think


fetch(url)
  .then((resp)=> resp.json())
  .then(function(data){

    //create and append the list to the ul
    let authors = data.results; // get results

    return collections.map(function(collection){

      let card = createNode('div'),
        //  img = createNode('img'),
          h1 = createNode('h1');

          card.setAttribute('class', 'card');

      img.src = collection.notes.value;
      h1.innerHTML = `${collection.notes.value} ${collection.notes.value}`;

      append(card, h1);
      append(div, card);

    })
  })

.catch(function(error){
  console.log(error)
});

标签: javascriptjsonapifetch

解决方案


对于那些寻求帮助的人,我发现这个答案很有帮助 -尝试从 REST API 获取数据时,请求的资源上不存在“Access-Control-Allow-Origin”标头

我通过代码更改为以下内容并成功返回了我期望的 json:

const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "http://collections.anmm.gov.au/collections/json"; // site that doesn’t send Access-Control-*
fetch(proxyurl + url) // https://cors-anywhere.herokuapp.com/https://example.com
.then(response => response.json())
.then(contents => console.log(contents))

.then(function(data){

  let authors = data.results;
console.log(authors);
  return authors.map(function(author){

    let card = createNode('div'),
      //  img = createNode('img'),
        h1 = createNode('h1');

        card.setAttribute('class', 'card');

  //  img.src = author.picture.medium;
    h1.innerHTML = `${author.name.first} ${author.name.last}`; 
    //append(card, img); // append all our elements
    append(card, h1);
    append(div, card);

  })
})


.catch(() => console.log("Can’t access " + url + " response. Blocked by browser?"))

推荐阅读