跳至內容

API 路由

範例

注意事項:如果您正在使用應用程式路由器,您可以使用伺服器組件路由處理程式來取代 API 路由。

API 路由提供了一個使用 Next.js 建立公開 API 的解決方案。

pages/api 資料夾中的任何檔案都會映射到 /api/*,並會被視為 API 端點而不是頁面。它們是僅限伺服器端的套件,不會增加您的客戶端套件大小。

例如,以下 API 路由會返回狀態碼為 200 的 JSON 回應

pages/api/hello.ts
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!' })
}

注意事項:

參數

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  // ...
}

HTTP 方法

要在 API 路由中處理不同的 HTTP 方法,您可以在請求處理程式中使用 req.method,如下所示:

pages/api/hello.ts
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 是一個明確的旗標,用於告知伺服器此路由是由外部解析器(例如 expressconnect)處理。啟用此選項將停用未解析請求的警告。

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 可以是 stringobjectBuffer
  • res.redirect([status,] path) - 重新導向至指定的路径或 URL。status 必須是有效的 HTTP 狀態碼。如果未指定,status 預設為「307」「暫時重新導向」。
  • res.revalidate(urlPath) - 使用 getStaticProps 依需求重新驗證頁面urlPath 必須是 string

設定回應的狀態碼

當發送回應回客戶端時,您可以設定回應的狀態碼。

以下範例將回應的狀態碼設定為 200 (OK),並以 JSON 回應的形式返回一個值為 Hello from Next.js!message 屬性。

pages/api/hello.ts
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 區塊中,以處理可能發生的任何錯誤,並將捕獲到的適當狀態碼和錯誤訊息發送回客戶端。

pages/api/hello.ts
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 回應,以及非同步操作的結果。

pages/api/hello.ts
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
pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { name, message } = req.body
 
  try {
    await handleFormInputAsync({ name, message })
    res.redirect(307, '/')
  } catch (err) {
    res.status(500).send({ error: 'Failed to fetch data' })
  }
}

新增 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!' })
}

注意事項:`NextApiRequest` 的主體是 `any`,因為客戶端可能會包含任何有效負載。您應該在使用主體之前,在執行時驗證其類型/形狀。

動態 API 路由

API 路由支援動態路由,並遵循與 `pages/` 相同的檔案命名規則。

pages/api/post/[pid].ts
import type { NextApiRequest, NextApiResponse } from 'next'
 
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const { pid } = req.query
  res.end(`Post: ${pid}`)
}

現在,對 `/api/post/abc` 的請求將會回應文字:`Post: abc`。

全域捕捉 API 路由

可以透過在括號內添加三個點 ( `...` ) 來擴展 API 路由以捕捉所有路徑。例如

注意事項:您可以使用 `slug` 以外的名稱,例如:`[...param]`

匹配的參數將作為查詢參數(範例中的 `slug`)發送到頁面,它始終是一個陣列,因此,路徑 `/api/post/a` 將具有以下 `query` 物件

{ "slug": ["a"] }

在 `/api/post/a/b` 和任何其他匹配路徑的情況下,新的參數將被添加到陣列中,如下所示

{ "slug": ["a", "b"] }

例如

pages/api/post/[...slug].ts
import type { NextApiRequest, NextApiResponse } from 'next'
 
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const { slug } = req.query
  res.end(`Post: ${slug.join(', ')}`)
}

現在,對 `/api/post/a/b/c` 的請求將會回應文字:`Post: a, b, c`。

可選的全域捕捉 API 路由

可以透過將參數包含在雙括號中 ( `[[...slug]]` ) 來使全域捕捉路由成為可選的。

例如,`pages/api/post/[[...slug]].js` 將匹配 `/api/post`、`/api/post/a`、`/api/post/a/b` 等等。

全域捕捉和可選的全域捕捉路由之間的主要區別在於,使用可選的全域捕捉,沒有參數的路由也會被匹配(例如上述範例中的 `/api/post`)。

`query` 物件如下所示

{ } // GET `/api/post` (empty object)
{ "slug": ["a"] } // `GET /api/post/a` (single-element array)
{ "slug": ["a", "b"] } // `GET /api/post/a/b` (multi-element array)

注意事項

邊緣 API 路由

如果您想將 API 路由與邊緣運行時搭配使用,我們建議逐步採用應用程式路由器,並改用路由處理程式

路由處理程式的函式簽章是同構的,這表示您可以將相同的函式用於邊緣和 Node.js 運行時。