表單與資料異動

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

小知識:

範例

僅限伺服器的表單

使用 Pages 路由時,您需要手動建立 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">Submit</button>
    </form>
  )
}

表單驗證

我們推薦使用 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)
  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 ? '載入中...' : '提交'}
        </button>
      </form>
    </div>
  )
}

顯示載入狀態

您可以使用 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) // 請求開始時設為載入中

    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) // 請求完成時設為非載入中
    }
  }

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

您可以在 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