如何使用 API 路由建立表單
表單允許您在 Web 應用程式中建立和更新資料。Next.js 提供了一種使用 API 路由處理資料變更的強大方式。本指南將引導您瞭解如何在伺服器上處理表單提交。
伺服器表單
要在伺服器上處理表單提交,請建立一個安全地修改資料的 API 端點。
pages/api/submit.ts
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 路由
pages/index.tsx
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 驗證,例如 `required` 和 `type="email"` 進行基本的客戶端表單驗證。
對於更高階的伺服器端驗證,您可以使用模式驗證庫(如 zod)在修改資料之前驗證表單欄位。
pages/api/submit.ts
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 state 在表單提交失敗時顯示錯誤訊息
pages/index.tsx
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) // Clear previous errors when a new request starts
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) {
// Capture the error message to display to the user
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>
)
}顯示載入狀態
您可以使用 React state 在表單在伺服器上提交時顯示載入狀態
pages/index.tsx
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) // Set loading to true when the request starts
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) // Set loading to false when the request completes
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? 'Loading...' : 'Submit'}
</button>
</form>
)
}重定向
如果您希望在變更後將使用者重定向到不同的路由,您可以 重定向 到任何絕對或相對 URL
pages/api/submit.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}這有幫助嗎?