介紹/指南/表單

如何使用 API 路由建立表單

表單能讓你在網頁應用程式中建立與更新資料。Next.js 提供了強大的方式來處理資料變更,使用 API 路由 (API Routes)。本指南將帶你了解如何在伺服器端處理表單提交。

伺服器表單

要在伺服器端處理表單提交,請建立一個 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,
    })

    // Handle response if necessary
    const data = await response.json()
    // ...
  }

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

須知事項:

  • API 路由 不會指定 CORS 標頭,這意味著它們預設僅允許同源請求。
  • 由於 API 路由在伺服器端執行,我們可以透過 環境變數 使用敏感值(如 API 金鑰)而不會暴露給客戶端。這對應用程式的安全性至關重要。

表單驗證

我們建議使用 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.')
      }

      // Handle response if necessary
      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) // 當請求開始時將載入狀態設為 true

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

      // Handle response if necessary
      const data = await response.json()
      // ...
    } catch (error) {
      // Handle error if necessary
      console.error(error)
    } finally {
      setIsLoading(false) // 當請求完成時將載入狀態設為 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}`)
}

On this page