首页 > 解决方案 > 在 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

    
        }

标签: node.jsreactjsnext.js

解决方案


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 调用。


推荐阅读