node.js - 在 Next.js 中获取数据
问题描述
您不应该从 getStaticProps 获取 API 路由 - 相反,您可以直接在 getStaticProps 中编写服务器端代码。
上面这句话来自 next.js 的官方文档,我觉得它很混乱。
是不是说我不应该对我的 api 做 ajax 请求?(我使用 node express 应用程序作为后端)。
在我使用 mongodb 作为数据库的反应节点应用程序之前,我是 next.js 的新手。我使用 moongose 包进行数据库相关查询。
如果我不应该做 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 Routes 是 NextJS 的一项功能,可让您创建 API - 这需要本地服务器启动并进行侦听。
https://nextjs.org/docs/api-routes/introduction
getStaticProps
在构建时获取,意味着没有用户请求。它让NextJS在不需要用户请求的情况下生成 SSR 页面,由于服务器尚未启动,此时 API Routes 将不可用。
在你的例子中
//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 调用。
推荐阅读
- java - 使用扫描仪为另一个类中的变量赋值?
- python - Python 添加和获取魔法 (dunder) 方法
- android - 导航抽屉显示在我的活动中的视图下
- c++ - 我有 .lib 和 .dll 文件,但没有 .h - 如何在其他 C++ 项目中使用这些库中的方法?
- c++ - 多项式和偏差的c ++模板
- sqlite - 是否可以在 sqlite 中不显示没有内容的列?
- c# - API 制表器 - 汇总列值 - 单元格值编辑的动态总计
- webots - Webots 录制电影默认保存位置
- javascript - 在每个循环中使用 5 个元素,用完 100 个元素
- java - 简单的递归减法返回意外结果