表單與資料異動

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

須知事項:

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

範例

僅伺服器表單

使用頁面路由時,您需要手動建立 API 端點來安全地在伺服器上異動資料。

import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const data = req.body
  const id = await createItem(data)
  res.status(200).json({ id })
}

接著,從客戶端使用事件處理器呼叫 API 路由:

import { FormEvent } from 'react'

export default function Page() {
  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()

    const formData = new FormData(event.currentTarget)
    const response = await fetch('/api/submit', {
      method: 'POST',
      body: formData,
    })

    // 如有需要可處理回應
    const data = await response.json()
    // ...
  }

  return (
    <form onSubmit={onSubmit}>
      <input type="text" name="name" />
      <button type="submit">提交</button>
    </form>
  )
}

重新導向

若您想在異動後將使用者重新導向至不同路由,您可以使用 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}`)
}

表單驗證

我們建議使用 HTML 驗證如 requiredtype="email" 來進行基本表單驗證。

對於更進階的伺服器端驗證,可使用架構驗證函式庫如 zod 來驗證解析後表單資料的結構:

import type { NextApiRequest, NextApiResponse } from 'next'
import { z } from 'zod'

const schema = z.object({
  // ...
})

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const parsed = schema.parse(req.body)
  // ...
}

顯示載入狀態

您可以使用 React 狀態來顯示表單在伺服器提交時的載入狀態:

import React, { useState, FormEvent } from 'react'

export default function Page() {
  const [isLoading, setIsLoading] = useState<boolean>(false)

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setIsLoading(true) // 請求開始時設定載入為 true

    try {
      const formData = new FormData(event.currentTarget)
      const response = await fetch('/api/submit', {
        method: 'POST',
        body: formData,
      })

      // 如有需要可處理回應
      const data = await response.json()
      // ...
    } catch (error) {
      // 如有需要可處理錯誤
      console.error(error)
    } finally {
      setIsLoading(false) // 請求完成時設定載入為 false
    }
  }

  return (
    <form onSubmit={onSubmit}>
      <input type="text" name="name" />
      <button type="submit" disabled={isLoading}>
        {isLoading ? '載入中...' : '提交'}
      </button>
    </form>
  )
}

錯誤處理

您可以使用 React 狀態來顯示表單提交失敗時的錯誤訊息:

import React, { useState, FormEvent } from 'react'

export default function Page() {
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [error, setError] = useState<string | null>(null)

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setIsLoading(true)
    setError(null) // 當新請求開始時清除先前的錯誤

    try {
      const formData = new FormData(event.currentTarget)
      const response = await fetch('/api/submit', {
        method: 'POST',
        body: formData,
      })

      if (!response.ok) {
        throw new Error('Failed to submit the data. Please try again.')
      }

      // 如有需要,處理回應
      const data = await response.json()
      // ...
    } catch (error) {
      // 捕捉錯誤訊息以顯示給使用者
      setError(error.message)
      console.error(error)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div>
      {error && <div style={{ color: 'red' }}>{error}</div>}
      <form onSubmit={onSubmit}>
        <input type="text" name="name" />
        <button type="submit" disabled={isLoading}>
          {isLoading ? 'Loading...' : 'Submit'}
        </button>
      </form>
    </div>
  )
}

您可以在 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 has been set.')
}

您可以在 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 has been deleted.')
}

On this page