【发布时间】:2021-08-10 08:16:40
【问题描述】:
我正在开发一个 NextJS 应用程序,我正在尝试使用 NextJS 的内置 API 路由功能来伪造一个后端 API 服务器。我的数据在src/pages/api/categories.js
// in src/pages/api/categories.js
export default (_req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
data: [
{ id: 1, title: "Category 1", imgUrl: "/demo-bg.jpg", url: "#" },
// and so on
]
}));
}
使用src/pages/categories.js中获取的数据的组件
// in src/pages/categories.js
function Categories({ categories }) {
return (
<section>
{
categories.map(({ id, title, imgUrl, url }) => {
return (
<div key={id}>
<div>{title}</div>
</div>
)
})
}
</section>
);
}
export async function getStaticProps() {
const res = await fetch(`http://localhost:3000/api/categories`);
const data = await res.json();
const categories = data.data;
if (!categories) {
return { notFound: true }
}
return {
props: { categories },
}
}
export default Categories;
在运行我的服务器时,我遇到了运行时错误TypeError: Cannot read property 'map' of undefined。传递给Categories 组件的categories 属性未定义。
但是当我从http://localhost:8000/api/categories 的 Django REST 服务器获取 API 时返回相同的 JSON 格式,即{ "data": [ { "id": 1, "title": "Category 1", imgUrl: "/demo-bg.jpg", url: "#" } ] },它工作正常。
我在这里做错了什么?任何帮助将不胜感激。
【问题讨论】:
-
你的意思是你已经建立了一个自定义服务器?我不确定你为什么使用端口 3000 和 8000。
-
我不知道它是否会有所帮助,但请尝试
fetch('/api/categories')。由于您的应用位于 localhost:3000 上,因此您无需调用完整的 url。我没有看到任何其他问题。 -
@nico 8000 是真正的后端。我的后端开发人员落后了,所以我继续使用 nextjs api 路由功能创建自己的假后端服务器
-
@PrakharJain 感谢您的建议。不幸的是,现在发生了同样的错误。
-
@dEBAM 您应该避免从
getStaticProps/getServerSideProps调用内部 API 路由。你应该call the logic directly,因为它们已经在服务器端运行了。