Next.js - API 中介軟體



Next.JS 中的 API 路由具有內建中介軟體,可幫助解析傳入的請求。

以下是中介軟體

  • req.cookies - cookies 物件包含請求傳送的 cookies。預設值為 {}。

  • req.query - query 物件包含查詢字串。預設值為 {}。

  • req.body - query 物件包含使用“content-type”解析的請求主體。預設值為 null。

我們建立一個示例來演示相同的程式碼。

在此示例中,我們將更新 **pages/api** 目錄中的 user.js。

讓我們更新 API 路由 章節中使用的 nextjs 專案。

按照以下方式在 pages/api 目錄中建立 user.js 檔案。

export default (req, res) => {
   res.statusCode = 200
   res.setHeader('Content-Type', 'application/json')
   res.end(JSON.stringify({ query: req.query }))
}

啟動 Next.js 伺服器

執行以下命令以啟動伺服器 -。

npm run dev

> nextjs@1.0.0 dev D:\Node\nextjs
> next

ready - started server on https://:3000
info  - Loaded env from D:\Node\nextjs\.env.local
event - compiled successfully
event - build page: /api/user
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

驗證輸出

在瀏覽器中開啟 https://:3000/api/user?counter=1,您將看到以下輸出。

{"query":{"counter":"1"}}
廣告
© . All rights reserved.