API 路由
API 路由提供了一個使用 Next.js 建立公開 API 的解決方案。
pages/api
資料夾中的任何檔案都會映射到 /api/*
,並會被視為 API 端點而不是頁面
。它們是僅限伺服器端的套件,不會增加您的客戶端套件大小。
例如,以下 API 路由會返回狀態碼為 200
的 JSON 回應
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
res.status(200).json({ message: 'Hello from Next.js!' })
}
注意事項:
- API 路由不會指定 CORS 標頭,這表示它們預設為僅限同源。您可以透過使用CORS 請求輔助工具包裝請求處理程式來自訂此類行為。
- API 路由不能與靜態匯出一起使用。但是,應用程式路由器中的路由處理程式可以。
- API 路由會受到
next.config.js
中的pageExtensions
設定的影響。
- API 路由會受到
參數
export default function handler(req: NextApiRequest, res: NextApiResponse) {
// ...
}
req
:http.IncomingMessage 的一個實例res
:http.ServerResponse 的一個實例
HTTP 方法
要在 API 路由中處理不同的 HTTP 方法,您可以在請求處理程式中使用 req.method
,如下所示:
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
// Process a POST request
} else {
// Handle any other HTTP method
}
}
請求輔助工具
API 路由提供內建的請求輔助工具,用於解析傳入的請求 (req
)
req.cookies
- 包含請求所傳送 cookie 的物件。預設為{}
req.query
- 包含查詢字串的物件。預設為{}
req.body
- 包含由content-type
解析的訊息主體的物件,如果沒有傳送訊息主體,則為null
自訂設定
每個 API 路由都可以匯出一個 config
物件來更改預設設定,如下所示:
export const config = {
api: {
bodyParser: {
sizeLimit: '1mb',
},
},
// Specifies the maximum allowed duration for this function to execute (in seconds)
maxDuration: 5,
}
bodyParser
預設為啟用。如果您想將訊息主體作為 Stream
或使用 raw-body
來使用,您可以將其設定為 false
。
停用自動 bodyParsing
的一個用例是允許您驗證**Webhook** 請求的原始訊息主體,例如來自 GitHub 的請求。
export const config = {
api: {
bodyParser: false,
},
}
bodyParser.sizeLimit
是解析後訊息主體允許的最大大小,以 bytes 支援的任何格式表示,如下所示:
export const config = {
api: {
bodyParser: {
sizeLimit: '500kb',
},
},
}
externalResolver
是一個明確的旗標,用於告知伺服器此路由是由外部解析器(例如 express 或 connect)處理。啟用此選項將停用未解析請求的警告。
export const config = {
api: {
externalResolver: true,
},
}
responseLimit
會自動啟用,當 API 路由的回應主體超過 4MB 時會發出警告。
如果您不在無伺服器環境中使用 Next.js,並且了解不使用 CDN 或專用媒體主機的效能影響,您可以將此限制設定為 false
。
export const config = {
api: {
responseLimit: false,
},
}
responseLimit
也可以接受位元組數或任何 bytes
支援的字串格式,例如 1000
、'500kb'
或 '3mb'
。此值將是顯示警告之前的最大回應大小。預設值為 4MB。(見上文)
export const config = {
api: {
responseLimit: '8mb',
},
}
回應輔助工具
伺服器回應物件(通常縮寫為 res
)包含一組類似 Express.js 的輔助方法,可改善開發體驗並提高建立新 API 端點的速度。
包含的輔助工具如下:
res.status(code)
- 設定狀態碼的函式。code
必須是有效的 HTTP 狀態碼res.json(body)
- 傳送 JSON 回應。body
必須是可 序列化的物件res.send(body)
- 傳送 HTTP 回應。body
可以是string
、object
或Buffer
res.redirect([status,] path)
- 重新導向至指定的路径或 URL。status
必須是有效的 HTTP 狀態碼。如果未指定,status
預設為「307」「暫時重新導向」。res.revalidate(urlPath)
- 使用getStaticProps
依需求重新驗證頁面。urlPath
必須是string
。
設定回應的狀態碼
當發送回應回客戶端時,您可以設定回應的狀態碼。
以下範例將回應的狀態碼設定為 200
(OK
),並以 JSON 回應的形式返回一個值為 Hello from Next.js!
的 message
屬性。
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
res.status(200).json({ message: 'Hello from Next.js!' })
}
發送 JSON 回應
當發送回應回客戶端時,您可以發送 JSON 回應,這必須是一個可序列化物件。在實際應用中,您可能希望根據請求端點的結果讓客戶端知道請求的狀態。
以下範例發送一個狀態碼為 200
(OK
) 的 JSON 回應,以及非同步操作的結果。它包含在一個 try-catch 區塊中,以處理可能發生的任何錯誤,並將捕獲到的適當狀態碼和錯誤訊息發送回客戶端。
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const result = await someAsyncOperation()
res.status(200).json({ result })
} catch (err) {
res.status(500).json({ error: 'failed to load data' })
}
}
發送 HTTP 回應
發送 HTTP 回應的方式與發送 JSON 回應相同。唯一的區別是回應主體可以是 字串
、物件
或 Buffer
。
以下範例發送一個狀態碼為 200
(OK
) 的 HTTP 回應,以及非同步操作的結果。
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const result = await someAsyncOperation()
res.status(200).send({ result })
} catch (err) {
res.status(500).send({ error: 'failed to fetch data' })
}
}
重新導向到指定的路径或 URL
新增 TypeScript 類型 import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
res.status(200).json({ message: 'Hello from Next.js!' })
}
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
res.status(200).json({ message: 'Hello from Next.js!' })
}