我正在尝试使用 getStaticProps 和 next js 从 api 获取一些数据。它返回错误 undefined cannot be serialized as JSON. Please usenull` 或省略此值。
我已经根据网上提出的有关该主题的解决方案修改了代码,但它们都不起作用。
export async function getStaticProps() {
const propertyForSale = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-sale&hitsPerPage=6`);
const propertyForRent = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-rent&hitsPerPage=6`);
return {
props: {
// Initial code
propertyForSale: propertyForSale?.hits,
propertyForRent: propertyForRent?.hits,
// the below snippet fixes the issue but return null
// propertyForSale: propertyForSale?.hits ?? null,
//propertyForRent: propertyForRent?.hits ?? null,
//the below snippet fixes the issue but return Unexpected token u in JSON at position 0
// propertyForSale: JSON.stringify(JSON.parse(propertyForSale?.hits))
//propertyForRent: JSON.stringify(JSON.parse(propertyForRent?.hits)),
}
}
}
Run Code Online (Sandbox Code Playgroud)
fetchapi.js
export const baseUrl = 'https://bayut.p.rapidapi.com'
export const fetchApi = async (url) => {
const {result} = await axios.get((url), {
headers: {
'x-rapidapi-host': 'bayut.p.rapidapi.com',
'x-rapidapi-key': process.env.NEXT_PUBLIC_BAYU_API
},
});
console.log(result);
return result;
};
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以试试这个吗?
return {
props: {
propertyForSale: propertyForSale?.hits || null,
propertyForRent: propertyForRent?.hits || null,
}
}
Run Code Online (Sandbox Code Playgroud)
为了修复该错误,我将常量结果重命名为数据,如下所示。我不确定这个错误的原因是什么,如果有人想添加一些东西来解释命名常量数据修复错误的原因,我的猜测是。
export const fetchApi = async (url) => {
const {data} = await axios.get((url), {
headers: {
'x-rapidapi-host': 'bayut.p.rapidapi.com',
'x-rapidapi-key': process.env.NEXT_PUBLIC_BAYU_API
},
});
return data;
};
Run Code Online (Sandbox Code Playgroud)
export async function getStaticProps() {
const propertyForSale = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-sale&hitsPerPage=6`);
const propertyForRent = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-rent&hitsPerPage=6`);
return {
props: {
// Initial code
propertyForSale: propertyForSale?.hits,
propertyForRent: propertyForRent?.hits,
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22372 次 |
| 最近记录: |