[英]fetching data in Next.js
您不应该从 getStaticProps 获取 API 路由 - 相反,您可以直接在 getStaticProps 中编写服务器端代码。
上面这句话来自 next.js 的官方文档,我觉得它很混乱。
是不是说我不应该对我平静的 api 提出 ajax 请求? (我使用 node express 应用程序作为后端)。
在我使用带有 mongodb 作为数据库的反应节点应用程序之前,我是 next.js 的新手。 我使用月光 package 进行数据库相关查询。
如果我不应该执行 ajax 请求,那么我应该如何处理数据获取相关的事情? 我可以直接在前端使用月光吗?
//the way i want to do
getStaticProps(){
//here i want to get data from database about posts
//fetch('some end point of my restful api'){...}
}
//the way i think official docs is telling me to do
getStaticProps(){
//query from database
}
API 路由是 NextJS 的一项功能,可让您创建 API - 这需要本地服务器启动并监听。
https://nextjs.org/docs/api-routes/introduction
getStaticProps
在构建时获取,意味着没有用户请求。 它让NextJS在不需要用户请求的情况下生成 SSR 页面,API 由于服务器尚未启动,此时路由将不可用。
在你的例子中
//here i want to get data from database about posts
//fetch('some end point of my restful api'){...}
// 1.Write your data from database
// 2. Instead of `fetch` - Write logic of your restful api if
its internal or the external endpoint that doesn't
need the instantiation of your server.
希望差异有意义,您可以进行fetch
调用,只是它们不应该是您的服务器本身正在创建的东西。 把它想象成一个构建时间的 fetch 调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.