我使用 Next.js / React.js。我正在使用此 API 获取特定国家:链接。
响应中有一个名为 borders 的数组,例如。
响应中有一个名为 borders 的数组,例如。
borders: [
"CAN",
"MEX",
],
有一个基于边界获取数据的终点,例如。
https://restcountries.eu/rest/v2/alpha/can
我该如何获取两个边界的数据,即边界数组中的每个元素? 我尝试在循环中进行两个API调用,但是我得到了未定义的结果。
export async function getServerSideProps(context) {
const { name } = context.params;
const res = await fetch(`https://restcountries.eu/rest/v2/name/${name}?fullText=true`)
const countryRes = await res.json();
const country = countryRes[0];
// Get the borders
const borders = country.borders;
// I'm making an API call to each element in array
const borderCountr = borders.forEach(border => {
fetch(`https://restcountries.eu/rest/v2/alpha/${border}`);
});
console.log(borderCountr); // undefinded
if (!country) {
return {
notFound: true,
}
}
return {
props: { country }
}
}
Array.forEach
doesn't return anything. You needconst borderCountr = await Promise.all(borders.map => fetch(...).then(r => r.json()));
- user5734311