表單和變更
表單讓您可以在網頁應用程式中建立和更新資料。Next.js 提供使用API 路由處理表單提交和資料變更的強大方法。
注意事項
- 我們很快就會建議您逐步採用應用程式路由器,並使用伺服器動作來處理表單提交和資料變更。伺服器動作讓您可以定義可以直接從元件呼叫的非同步伺服器函式,而無需手動建立 API 路由。
- API 路由 並未指定 CORS 標頭,這表示它們預設僅限同源。
- 由於 API 路由在伺服器上運行,我們可以使用敏感值(例如 API 金鑰),透過 環境變數,而不會將它們暴露給客戶端。這對應用程式的安全性至關重要。
範例
僅限伺服器端表單
然後,使用事件處理程式從客戶端呼叫 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>
)
}
表單驗證
我們建議使用 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 狀態在表單提交失敗時顯示錯誤訊息。
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 狀態來顯示載入狀態。
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>
)
}
重新導向
如果您想要在變異後將使用者重新導向到不同的路由,您可以使用redirect
到任何絕對或相對 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}`)
}
設定 Cookie
您可以在 API 路由中使用回應上的 setHeader
方法來設定 Cookie。
pages/api/cookie.ts
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.')
}
讀取 Cookie
您可以在 API 路由中使用cookies
請求輔助程式來讀取 Cookie。
pages/api/cookie.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const auth = req.cookies.authorization
// ...
}
刪除 Cookie
您可以在 API 路由中使用回應上的 setHeader
方法來刪除 Cookie。
pages/api/cookie.ts
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.')
}