表單與資料異動

表單讓您能在網頁應用程式中建立與更新資料。Next.js 提供了強大的方式來處理表單提交與資料異動,使用的是 API 路由

小知識:

  • 我們很快會推薦您逐步採用 App Router,並使用伺服器動作 (Server Actions)來處理表單提交與資料異動。伺服器動作讓您能直接從元件中呼叫非同步伺服器函式,無需手動建立 API 路由。
  • API 路由不會指定 CORS 標頭,這表示預設情況下它們僅限同源請求。
  • 由於 API 路由在伺服器端執行,我們可以透過環境變數使用敏感值(如 API 金鑰)而不會暴露給客戶端。這對應用程式的安全性至關重要。

範例

重新導向

若您想在資料異動後將使用者重新導向至不同路由,可以使用 redirect 導向任何絕對或相對 URL:

import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const id = await addPost()
  res.redirect(307, `/post/${id}`)
}

您可以在 API 路由中使用回應的 setHeader 方法設定 cookie:

import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  res.setHeader('Set-Cookie', 'username=lee; Path=/; HttpOnly')
  res.status(200).send('Cookie 已設定。')
}

您可以在 API 路由中使用 cookies 請求輔助工具讀取 cookie:

import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const auth = req.cookies.authorization
  // ...
}

您可以在 API 路由中使用回應的 setHeader 方法刪除 cookie:

import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  res.setHeader('Set-Cookie', 'username=; Path=/; HttpOnly; Max-Age=0')
  res.status(200).send('Cookie 已刪除。')
}

On this page