表单与数据变更 (Forms and Mutations)

表单让您能够在网页应用中创建和更新数据。Next.js 通过 API 路由 提供了强大的表单提交与数据变更处理方案。

须知:

  • 我们即将推荐 渐进式迁移 到应用路由,并使用 服务端操作 (Server Actions) 处理表单提交与数据变更。服务端操作允许您定义异步服务端函数,无需手动创建 API 路由即可直接从组件调用。
  • API 路由 默认不指定 CORS 头信息,意味着默认仅支持同源请求。
  • 由于 API 路由在服务端运行,可通过 环境变量 使用敏感值(如 API 密钥)而不会暴露给客户端,这对应用安全性至关重要。

示例

纯服务端表单

使用页面路由时,您需要手动创建 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,
    })

    // 如需处理响应
    const data = await response.json()
    // ...
  }

  return (
    <form onSubmit={onSubmit}>
      <input type="text" name="name" />
      <button type="submit">提交</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}`)
}

表单验证

推荐使用 requiredtype="email" 等 HTML 验证进行基础表单验证。

如需高级服务端验证,可使用 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)

  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>
  )
}

错误处理

您可以使用 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>
  )
}

设置 Cookies

您可以在 API 路由中使用响应对象的 setHeader 方法设置 cookie:

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 已设置。')
}

读取 Cookies

您可以在 API 路由中使用 cookies 请求辅助函数读取 cookie:

import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const auth = req.cookies.authorization
  // ...
}

删除 Cookies

您可以在 API 路由中使用响应对象的 setHeader 方法删除 cookie:

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 已删除。')
}

On this page