消费API-如何连接到API

时间:2018-07-03 15:56:16

标签: javascript fetch-api urlfetch

我已经编写了大部分代码,但是不确定这是怎么做的:

let url = 'https://cors-anywhere.herokuapp.com/https://newsapi.org/v2/top-headlines?sources=hacker-news&apiKey=3dcfcd098261443dae7c7d002f25c062';

fetch(url)
  .then(r =>{
  return r.json();
})

  .then(data => {
    let articles = data.articles;
    let storyList = document.createElement("ul");
    let body = document.querySelector("body");
    body.appendChild(storyList);
})
  articles.map(articles => {
    let storyItem = document.createElement("li");
    storyItem.innerHTML = 'a href = "' + articles.href + '">' + articles.title + "</a>";
      storyList.appendChild(storyItem);
  })

  .catch(e => {
    console.log('An error has occurred: ${e}');
});

我已经从API代码中取出了< >,并试图进行一些切换,例如切换一些属性以表示不同的内容,但是有人可以帮助我更好地理解这一点吗?预先感谢!

1 个答案:

答案 0 :(得分:0)

您做错了几件事。

  • 当您使用的API允许cors请求时,无需使用代理。
  • 您正在尝试访问超出范围且在诺言解决之前的“文章”
  • 您在“ articles”数组上使用了错误的方法IMO。从这里:Array.prototype.map()

      

    map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

    但是您没有尝试创建新的数组,您只想迭代该数组的元素。这就是Array.prototype.forEach()的目的。

  • 您在模板文字上使用了单引号',而不是反引号`

let url = 'https://newsapi.org/v2/top-headlines?sources=hacker-news&apiKey=3dcfcd098261443dae7c7d002f25c062';

fetch(url)
.then(response => {
    return response.json();
})
.then(data => {
    let list = document.createElement('ul');

    document.querySelector("body").appendChild(list);

    data.articles.forEach(article => {
        let item = document.createElement('li');
        item.innerHTML = '<a href="' + article.url + '">' + article.title + "</a>";
        list.appendChild(item);
    });
})
.catch(e => {
    console.log(`An error has occurred: ${e}`);
});