簡體   English   中英

在 Next.js 中獲取數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM