用于从API获取JSON数据的URL格式

2ul0zpep  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(94)

我是新的使用API和各种方法来获取数据.我一直在遵循一对夫妇的教程,包括this one on fetch method上或XMLHttpRequest方法来获取数据,并可以做到这一点,只是在教程中使用的API.我希望使用this api,但遇到了麻烦,我认为只是URL的形式.我得到这个错误:
“CORS策略已阻止从源'http://localhost:8888'获取'http://collections.anmm.gov.au/collections'的访问:No 'Excell-Control-Allow-Origin'“
我尝试使用“https”来避免CORS错误,但随后得到此错误:
net::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)
});

字符串

zvokhttg

zvokhttg1#

对于那些寻求帮助的人,我发现这个答案很有帮助-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?"))

字符串

相关问题