表单与数据变更

表单使您能够在 Web 应用中创建和更新数据。Next.js 通过 API 路由 (API Routes) 提供了一种强大的方式来处理表单提交和数据变更操作。

须知:

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

示例

重定向

如果您希望在数据变更后将用户重定向到其他路由,可以使用 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}`)
}

您可以在 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 已设置。')
}

您可以在 API 路由中使用 cookies 请求辅助方法读取 Cookie:

import type { NextApiRequest, NextApiResponse } from 'next'

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

您可以在 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