形式和突变
¥Forms and Mutations
表单使你能够在 Web 应用中创建和更新数据。Next.js 提供了一种使用 API 路由处理表单提交和数据突变的强大方法。
¥Forms enable you to create and update data in web applications. Next.js provides a powerful way to handle form submissions and data mutations using API Routes.
需要了解:
¥Good to know:
我们很快将推荐 逐步采用 App Router 并使用 服务器操作 来处理表单提交和数据突变。服务器操作允许你定义可以直接从组件调用的异步服务器函数,而无需手动创建 API 路由。
¥We will soon recommend incrementally adopting the App Router and using Server Actions for handling form submissions and data mutations. Server Actions allow you to define asynchronous server functions that can be called directly from your components, without needing to manually create an API Route.
API 路由 不指定 CORS 标头,这意味着它们仅在默认情况下是同源的。
¥API Routes do not specify CORS headers, meaning they are same-origin only by default.
由于 API 路由在服务器上运行,因此我们能够通过 环境变量 使用敏感值(例如 API 密钥),而无需将它们暴露给客户端。这对于应用的安全至关重要。
¥Since API Routes run on the server, we're able to use sensitive values (like API keys) through Environment Variables without exposing them to the client. This is critical for the security of your application.
示例
¥Examples
重定向
¥Redirecting
如果你想在更改后将用户重定向到不同的路由,你可以 redirect
到任何绝对或相对 URL:
¥If you would like to redirect the user to a different route after a mutation, you can redirect
to any absolute or relative 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}`)
}
设置 cookie
¥Setting cookies
你可以使用响应上的 setHeader
方法在 API 路由内设置 cookie:
¥You can set cookies inside an API Route using the setHeader
method on the response:
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.')
}
读取 cookies
¥Reading cookies
你可以使用 cookies
请求辅助程序读取 API 路由内的 cookie:
¥You can read cookies inside an API Route using the cookies
request helper:
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const auth = req.cookies.authorization
// ...
}
删除 cookies
¥Deleting cookies
你可以使用响应中的 setHeader
方法删除 API 路由内的 cookie:
¥You can delete cookies inside an API Route using the setHeader
method on the response:
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.')
}