用于从api获取json数据的url格式

时间:2018-10-31 10:50:53

标签: javascript json api fetch

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

  

“可以从以下位置获取'http://collections.anmm.gov.au/collections处的内容”   原产地“ http://localhost:8888”已被CORS政策禁止:否   'Access-Control-Allow-Origin'“

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

  

net :: ERR_CONNECTION_REFUSED。

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

我想知道的是,我所尝试的网址是否有问题,或者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)
});

1 个答案:

答案 0 :(得分:0)

对于那些寻求帮助的人,我发现此答案很有帮助-No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

我通过代码更改为以下内容,并成功返回了我期望的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?"))