开发者

How to fetch api with javascript to display data?

I am trying to build an API with javascript to fetch data from this URL for json data: img, a, c . But below codes threw back an error of

application.js:10 Uncaught (in promise) TypeError: data.forEach is not a function

(why is the forEach method not defined) can you help? thanks

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/")
  .then(response => response.json())
  .then((data) => {

    data.forEach((result) => {

      const movies = '<li><img src="' + result.im + '" alt=""><h3>' + result.a + '</开发者_StackOverflowh3><p>' + result.c + '</p></li>';
      results.insertAdjacentHTML("beforeend", movies);

    });
  });
{
  "a": "shoujo-apocalypse-adventure",
  "c": [
    "Adventure",
    "Drama",
    "Psychological",
    "Sci-fi",
    "Seinen",
    "Slice of Life",
    "Tragedy"
  ],
  "h": 156,
  "i": "5c410d31719a16035a4647cc",
  "im": "4a/4a1f2a595e0e84e62f6ceddf3946274478928ca99e8df86bc6511b6e.png",
  "ld": 1547822837.0,
  "s": 2,
  "t": "Shoujo Apocalypse Adventure"
},


The response is not an array ([]) but an object ({}) and object has no method forEach. I guess you meant to run the forEach on the entries, which in this case is under data.manga.

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/", {
    mode: 'cors'
  })
  .then(response => response.json())
  .then((data) => {

    data.manga
      .filter(movie => movie.c.includes('Action') || movie.c.includes('Adventure'))
      .slice(0, 10).forEach((result) => {

      const movies = '<li><img src="https://cdn.mangaeden.com/mangasimg/' + result.im + '" alt=""><h3>' + result.a + '</h3><p>' + result.c + '</p></li>';
      results.insertAdjacentHTML("beforeend", movies);

    });
  });
<ul id="results"></ul>

https://jsbin.com/gecusi/edit?html,js

Note: In the example I slice the array because there are ~6.7k movies and I don't want to block the browser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜