如何使用 API 路由创建表单
表单使你能够在 Web 应用程序中创建和更新数据。Next.js 提供了使用 API 路由 处理数据变更的强大方式。本指南将指导你如何在服务端处理表单提交。
服务端表单
要在服务端处理表单提交,创建一个 API 端点来安全地变更数据。
- TypeScript
- JavaScript
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 })
}
pages/api/submit.js
export default function handler(req, res) {
const data = req.body
// 调用你的数据库等
// const id = await createItem(data)
// ...
res.status(200).json({ data })
}
然后,使用事件处理器从客户端调用 API 路由:
- TypeScript
- JavaScript
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,
})
// 如有必要,处理响应
const data = await response.json()
// ...
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit">提交</button>
</form>
)
}
pages/index.jsx
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">提交</button>
</form>
)
}
提示:
- API 路由不指定 CORS 头,这意味着它们默认情况下仅限同源。
- 由于 API 路由在服务端运行,我们能够通过环境变量使用敏感值(如 API 密钥),而不会将它们暴露给客户端。这对应用程序的安全性至关重要。
表单验证
我们建议使用 HTML 验证,如 required
和 type="email"
进行基本的客户端表单验证。
对于更高级的服务端验证,你可以使用模式验证库,如 zod,在变更数据之前验证表单字段:
- TypeScript
- JavaScript
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)
// ...
}
pages/api/submit.js
import { z } from 'zod'
const schema = z.object({
// ...
})
export default async function handler(req, res) {
const parsed = schema.parse(req.body)
// ...
}
错误处理
你可以使用 React 状态在表单提交失败时显示错误消息:
- TypeScript
- JavaScript
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) // 当新请求开始时清除之前的错误
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error('提交数据失败。请重试。')
}
// 如有必要,处理响应
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>
)
}
pages/index.jsx
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('提交数据失败。请重试。')
}
// 如有必要,处理响应
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 状态在表单在服务端提交时显示加载状态:
- TypeScript
- JavaScript
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) // 当请求开始时设置加载为 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) // 当请求完成时设置加载为 false
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? '加载中...' : '提交'}
</button>
</form>
)
}
pages/index.jsx
import React, { useState } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState(false)
async function onSubmit(event) {
event.preventDefault()
setIsLoading(true) // 当请求开始时设置加载为 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) // 当请求完成时设置加载为 false
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? '加载中...' : '提交'}
</button>
</form>
)
}
重定向
如果你想在变更后将用户重定向到不同的路由,你可以使用 redirect
重定向到任何绝对或相对 URL:
- TypeScript
- JavaScript
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}`)
}
pages/api/submit.js
export default async function handler(req, res) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}