JavaScript,获取,API

发布于 2025-02-08 17:20:10 字数 1572 浏览 1 评论 0原文

我想做以下操作:从此网站获取随机名称 https://swapi.dev/api /people/,我这样做了,我可以在HTML页面中看到它,然后我也想获得一个随机的星球,在这里我需要访问HomeWorld键,并返回链接,然后再返回链接i i格式化以获取一个随机的URL,从该网址中,我还必须在页面上显示该星球的名称。第一个获取效果很好,至少我认为,但是第三个。然后,然后是不起作用的,或者至少我不知道如何从HomeWorld URL访问信息。这是我第一次尝试fetch(),如果您可以帮助我告诉我在代码和不同的解决方案中做错了什么,但并非如此复杂,那将是很好的。

let randomNumber = Math.floor(Math.random()*9)


const fetchPromise = fetch("https://swapi.dev/api/people/");

let test
let test2
let planets = document.querySelector('#age')
fetchPromise
    .then((response) => {
        if (!response.ok) {
            throw new Error(`Http error: ${response.status}`);

        }
        return response.json();
    })
    .then((json) => {
        console.log(json.results[randomNumber].name)
        showRandomUserData(json)
        test = json.results[0].homeworld
        test = test.slice(0, -2)
        // console.log(test + randomNumber + "/");
        // console.log(test + "/" + randomNumber + "/");
        test = test + randomNumber + "/";
        return fetch(test)
        // return fetch("https://swapi.dev/api/planets/2/");
    })
    .then(response => response.json()).then(json =>
    {   test2=json.name
        console.log(test2);
        planets.innerHTML = test2
    }) 

showRandomUserData = (randomUser) => {
    document.querySelector("#name").innerHTML =
        randomUser.results[randomNumber].name;

}


已解决

I want to do the following: get a random name with fetch from this website https://swapi.dev/api/people/, which I did and I can see it in my html page then I want also to get a random planet, here I need to access the homeworld key, and to return the link, before returning the link I formatted to get a random URL and from this one I also have to show the name of the planet on my page. The first fetch works fine, at least I think but the third .then() is not working or at least I don't know how to access the information from the homeworld URL. This is my first time trying fetch() and it will be nice if you can help me telling where I did wrong in code and maybe different solutions but not so complicated.

let randomNumber = Math.floor(Math.random()*9)


const fetchPromise = fetch("https://swapi.dev/api/people/");

let test
let test2
let planets = document.querySelector('#age')
fetchPromise
    .then((response) => {
        if (!response.ok) {
            throw new Error(`Http error: ${response.status}`);

        }
        return response.json();
    })
    .then((json) => {
        console.log(json.results[randomNumber].name)
        showRandomUserData(json)
        test = json.results[0].homeworld
        test = test.slice(0, -2)
        // console.log(test + randomNumber + "/");
        // console.log(test + "/" + randomNumber + "/");
        test = test + randomNumber + "/";
        return fetch(test)
        // return fetch("https://swapi.dev/api/planets/2/");
    })
    .then(response => response.json()).then(json =>
    {   test2=json.name
        console.log(test2);
        planets.innerHTML = test2
    }) 

showRandomUserData = (randomUser) => {
    document.querySelector("#name").innerHTML =
        randomUser.results[randomNumber].name;

}


Solved

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧时浪漫 2025-02-15 17:20:10

这是一个简单的解决方案,它使用fetch()从这两个URL中获取数据,然后插入所有返回到网页的人和一个星球:

function myFetch(...args) {
    return fetch(...args).then(response => {
        if (!response.ok) {
            throw new Error(`fetch failed with status ${response.status}`);
        }
        return response.json();
    });
}

Promise.all([
    myFetch("https://swapi.dev/api/people/"),
    myFetch("https://swapi.dev/api/planets/2/")
]).then(([people, planet]) => {
    const peopleDiv = document.getElementById("people");
    let peopleHTML = "";
    for (let p of people.results) {
        peopleHTML += `<div>${p.name}</div>`;
    }
    peopleDiv.innerHTML = peopleHTML;
    
    const planetDiv = document.getElementById("planets");
    let planetHTML = `<div>${planet.name}</div>`;
    planetDiv.innerHTML = planetHTML;
}).catch(err => {
    console.log(err);
});
<div id="people"></div>
<hr>
<div id="planets"></div>

至于使用结果,人们URL返回一个看起来像这样的结构:

{
  count: 82,
  next: 'https://swapi.dev/api/people/?page=2',
  previous: null,
  results: [
    {
      name: 'Luke Skywalker',
      height: '172',
      mass: '77',
      hair_color: 'blond',
      skin_color: 'fair',
      eye_color: 'blue',
      birth_year: '19BBY',
      gender: 'male',
      homeworld: 'https://swapi.dev/api/planets/1/',
      films: [Array],
      species: [],
      vehicles: [Array],
      starships: [Array],
      created: '2014-12-09T13:50:51.644000Z',
      edited: '2014-12-20T21:17:56.891000Z',
      url: 'https://swapi.dev/api/people/1/'
    },
    {
      name: 'C-3PO',
      height: '167',
      mass: '75',
      hair_color: 'n/a',
      skin_color: 'gold',
      eye_color: 'yellow',
      birth_year: '112BBY',
      gender: 'n/a',
      homeworld: 'https://swapi.dev/api/planets/1/',
      films: [Array],
      species: [Array],
      vehicles: [],
      starships: [],
      created: '2014-12-10T15:10:51.357000Z',
      edited: '2014-12-20T21:17:50.309000Z',
      url: 'https://swapi.dev/api/people/2/'
    }
}

因此,您有people.results,这是一个数组,您可以访问people.results [n]代码>从该数组中获取项目。 的对象。


该项目将是一个

{
  name: 'Alderaan',
  rotation_period: '24',
  orbital_period: '364',
  diameter: '12500',
  climate: 'temperate',
  gravity: '1 standard',
  terrain: 'grasslands, mountains',
  surface_water: '40',
  population: '2000000000',
  residents: [
    'https://swapi.dev/api/people/5/',
    'https://swapi.dev/api/people/68/',
    'https://swapi.dev/api/people/81/'
  ],
  films: [
    'https://swapi.dev/api/films/1/',
    'https://swapi.dev/api/films/6/'
  ],
  created: '2014-12-10T11:35:48.479000Z',
  edited: '2014-12-20T20:58:18.420000Z',
  url: 'https://swapi.dev/api/planets/2/'
}

具有.name,的属性 您可以在planet.name中访问该对象上的属性。


请注意,人们的结果是分页的。总共有82个,但第一个结果只有10个。其余的带有其他页面的结果,例如https://swapi.dev/api/people/?page=2

Here's a simple solution that uses fetch() to grab data from both those URLs and then insert all the people and the one planet that is returned into your web page:

function myFetch(...args) {
    return fetch(...args).then(response => {
        if (!response.ok) {
            throw new Error(`fetch failed with status ${response.status}`);
        }
        return response.json();
    });
}

Promise.all([
    myFetch("https://swapi.dev/api/people/"),
    myFetch("https://swapi.dev/api/planets/2/")
]).then(([people, planet]) => {
    const peopleDiv = document.getElementById("people");
    let peopleHTML = "";
    for (let p of people.results) {
        peopleHTML += `<div>${p.name}</div>`;
    }
    peopleDiv.innerHTML = peopleHTML;
    
    const planetDiv = document.getElementById("planets");
    let planetHTML = `<div>${planet.name}</div>`;
    planetDiv.innerHTML = planetHTML;
}).catch(err => {
    console.log(err);
});
<div id="people"></div>
<hr>
<div id="planets"></div>

As for using the results, the people URL returns a structure that looks like this:

{
  count: 82,
  next: 'https://swapi.dev/api/people/?page=2',
  previous: null,
  results: [
    {
      name: 'Luke Skywalker',
      height: '172',
      mass: '77',
      hair_color: 'blond',
      skin_color: 'fair',
      eye_color: 'blue',
      birth_year: '19BBY',
      gender: 'male',
      homeworld: 'https://swapi.dev/api/planets/1/',
      films: [Array],
      species: [],
      vehicles: [Array],
      starships: [Array],
      created: '2014-12-09T13:50:51.644000Z',
      edited: '2014-12-20T21:17:56.891000Z',
      url: 'https://swapi.dev/api/people/1/'
    },
    {
      name: 'C-3PO',
      height: '167',
      mass: '75',
      hair_color: 'n/a',
      skin_color: 'gold',
      eye_color: 'yellow',
      birth_year: '112BBY',
      gender: 'n/a',
      homeworld: 'https://swapi.dev/api/planets/1/',
      films: [Array],
      species: [Array],
      vehicles: [],
      starships: [],
      created: '2014-12-10T15:10:51.357000Z',
      edited: '2014-12-20T21:17:50.309000Z',
      url: 'https://swapi.dev/api/people/2/'
    }
}

So, you have people.results which is an array and you can access people.results[n] to get an item from that array. That item will be an object which has properties like .name, .height, etc...


The specific planet URL you show returns a single planet object like this:

{
  name: 'Alderaan',
  rotation_period: '24',
  orbital_period: '364',
  diameter: '12500',
  climate: 'temperate',
  gravity: '1 standard',
  terrain: 'grasslands, mountains',
  surface_water: '40',
  population: '2000000000',
  residents: [
    'https://swapi.dev/api/people/5/',
    'https://swapi.dev/api/people/68/',
    'https://swapi.dev/api/people/81/'
  ],
  films: [
    'https://swapi.dev/api/films/1/',
    'https://swapi.dev/api/films/6/'
  ],
  created: '2014-12-10T11:35:48.479000Z',
  edited: '2014-12-20T20:58:18.420000Z',
  url: 'https://swapi.dev/api/planets/2/'
}

So, you access properties on that object as in planet.name.


Notice that the people results are paged. There are 82 total results, but only 10 come in this first result. The rest come with results for other pages such as https://swapi.dev/api/people/?page=2.

陌生 2025-02-15 17:20:10

类似于这个答案但是使用async/等待避免回调地狱。如果可以,请尝试使用此方法。 为什么

? href =“ https://stackoverflow.com/users/816620/jfriend00”> jfriend00 使用Promise> Promise.all,而不是单独的fetch呼叫,因为这使得获取可以并行发生。 了解更多

sandbox 进行测试并尝试

const fetchData = async (...args) => {
  try {
    const response = await fetch(...args);
    return response.json();
  } catch (err) {
    throw new Error(`fetch failed with status ${err?.message}`);
  }
};

const updateDOM = (people, planet) => {
  document.getElementById("people").innerHTML = 
   people.results.reduce((s, p) => s + `<div>${p.name}</div>`, "");
  document.getElementById("planets").innerHTML = `<div>${planet.name}</div>`;
};

const populateData = async () => {
  try {
    const [people, planet] = await Promise.all([
      fetchData("https://swapi.dev/api/people/"),
      fetchData("https://swapi.dev/api/planets/2/"),
    ]);

    // do stuff with 'people' or 'planet'
    // example, get
    // const firstPersonsHomeworld = people.results[0].homeworld;
    // console.log(firstPersonsHomeworld);
    // or
    // const planetName = planet.name;
    // console.log(planetName);

    updateDOM(people, planet);
  } catch (err) {
    // errorHandler(err);
    console.error(err);
  }
};

// start app
populateData();

Similar to this answer but using async/await to avoid callback hell. If you can, try using this approach. Why?

Excellent recommendation in that answer by jfriend00 to use Promise.all instead of separate fetch calls, as that enables fetching to happen in parallel. To know more.

sandbox to test and try

const fetchData = async (...args) => {
  try {
    const response = await fetch(...args);
    return response.json();
  } catch (err) {
    throw new Error(`fetch failed with status ${err?.message}`);
  }
};

const updateDOM = (people, planet) => {
  document.getElementById("people").innerHTML = 
   people.results.reduce((s, p) => s + `<div>${p.name}</div>`, "");
  document.getElementById("planets").innerHTML = `<div>${planet.name}</div>`;
};

const populateData = async () => {
  try {
    const [people, planet] = await Promise.all([
      fetchData("https://swapi.dev/api/people/"),
      fetchData("https://swapi.dev/api/planets/2/"),
    ]);

    // do stuff with 'people' or 'planet'
    // example, get
    // const firstPersonsHomeworld = people.results[0].homeworld;
    // console.log(firstPersonsHomeworld);
    // or
    // const planetName = planet.name;
    // console.log(planetName);

    updateDOM(people, planet);
  } catch (err) {
    // errorHandler(err);
    console.error(err);
  }
};

// start app
populateData();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文