表單與資料異動
表單讓您能在網頁應用程式中建立與更新資料。Next.js 提供了強大的方式來處理表單提交與資料異動,使用 API 路由 (API Routes)。
小知識:
- 我們即將推薦漸進式採用 App 路由並使用伺服器動作 (Server Actions)來處理表單提交與資料異動。伺服器動作讓您能直接從元件呼叫非同步伺服器函式,無需手動建立 API 路由。
- API 路由不指定 CORS 標頭,這表示預設僅允許同源請求。
- 由於 API 路由在伺服器端執行,我們能透過環境變數 (Environment Variables)使用敏感值(如 API 金鑰)而不暴露給客戶端。這對應用程式的安全性至關重要。
範例
僅限伺服器的表單
使用 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 })
}
export default function handler(req, res) {
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>
)
}
export default function Page() {
async function onSubmit(event) {
event.preventDefault()
const formData = new FormData(event.target)
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 驗證如 required
和 type="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)
// ...
}
import { z } from 'zod'
const schema = z.object({
// ...
})
export default async function handler(req, res) {
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>
)
}
import React, { useState } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
async function onSubmit(event) {
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>
)
}
import React, { useState } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState(false)
async function onSubmit(event) {
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}`)
}
export default async function handler(req, res) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}
設定 Cookie
您可以在 API 路由中使用回應的 setHeader
方法來設定 Cookie:
讀取 Cookie
您可以在 API 路由中使用 cookies
請求輔助工具來讀取 Cookie:
刪除 Cookie
您可以在 API 路由中使用回應的 setHeader
方法來刪除 Cookie: