操作
Added in:
astro@4.15
Astro Actions 允许你定义和调用具有类型安全性的后端函数。操作为你执行数据提取、JSON 解析和输入验证。与使用 API 端点 相比,这可以大大减少所需的样板量。
¥Astro Actions allow you to define and call backend functions with type-safety. Actions perform data fetching, JSON parsing, and input validation for you. This can greatly reduce the amount of boilerplate needed compared to using an API endpoint.
使用操作而不是 API 端点,实现客户端和服务器代码之间的无缝通信,并:
¥Use actions instead of API endpoints for seamless communication between your client and server code and to:
-
使用 Zod 验证 自动验证 JSON 和表单数据输入。
-
生成类型安全的函数以从客户端甚至 来自 HTML 表单操作 调用你的后端。无需手动
fetch()
调用。 -
使用
ActionError
对象标准化后端错误。
¥Basic usage
操作在从 src/actions/index.ts
导出的 server
对象中定义:
¥Actions are defined in a server
object exported from src/actions/index.ts
:
你的操作可作为 astro:actions
模块中的函数使用。导入 actions
并在 UI 框架组件、表单 POST 请求 中在客户端调用它们,或者在 Astro 组件中使用 <script>
标签。
¥Your actions are available as functions from the astro:actions
module. Import actions
and call them client-side within a UI framework component, a form POST request, or by using a <script>
tag in an Astro component.
调用操作时,它会返回一个对象,其中 data
包含 JSON 序列化结果,或 error
包含抛出的错误。
¥When you call an action, it returns an object with either data
containing the JSON-serialized result, or error
containing thrown errors.
编写你的第一个操作
Section titled 编写你的第一个操作¥Write your first action
按照以下步骤定义操作并在 Astro 页面中的 script
标记中调用它。
¥Follow these steps to define an action and call it in a script
tag in your Astro page.
-
Create a
src/actions/index.ts
file and export aserver
object. -
Import the
defineAction()
utility fromastro:actions
, and thez
object fromastro:schema
. -
Use the
defineAction()
utility to define agetGreeting
action. Theinput
property will be used to validate input parameters with a Zod schema and thehandler()
function includes the backend logic to run on the server. -
Create an Astro component with a button that will fetch a greeting using your
getGreeting
action when clicked. -
To use your action, import
actions
fromastro:actions
and then callactions.getGreeting()
in the click handler. Thename
option will be sent to your action’shandler()
on the server and, if there are no errors, the result will be available as thedata
property.
defineAction()
and its properties.
¥Organizing actions
项目中的所有操作都必须从 src/actions/index.ts
文件中的 server
对象导出。你可以内联定义操作,也可以将操作定义移动到单独的文件并导入它们。你甚至可以将相关函数分组到嵌套对象中。
¥All actions in your project must be exported from the server
object in the src/actions/index.ts
file. You can define actions inline or you can move action definitions to separate files and import them. You can even group related functions in nested objects.
例如,要将所有用户操作放在一起,你可以创建一个 src/actions/user.ts
文件并将 getUser
和 createUser
的定义嵌套在单个 user
对象中。
¥For example, to colocate all of your user actions, you can create a src/actions/user.ts
file and nest the definitions of both getUser
and createUser
inside a single user
object.
然后,你可以将此 user
对象导入你的 src/actions/index.ts
文件中,并将其作为顶层键添加到 server
对象以及任何其他操作:
¥Then, you can import this user
object into your src/actions/index.ts
file and add it as a top-level key to the server
object alongside any other actions:
现在,你的所有用户操作都可以从 actions.user
对象调用:
¥Now, all of your user actions are callable from the actions.user
object:
-
actions.user.getUser()
-
actions.user.createUser()
处理返回的数据
Section titled 处理返回的数据¥Handling returned data
操作返回一个对象,其中包含 data
和 handler()
的类型安全返回值,或包含任何后端错误的 error
。错误可能来自 input
属性上的验证错误或 handler()
中抛出的错误。
¥Actions return an object containing either data
with the type-safe return value of your handler()
, or an error
with any backend errors. Errors may come from validation errors on the input
property or thrown errors within the handler()
.
¥Checking for errors
最好在使用 data
属性之前检查是否存在 error
。这允许你提前处理错误并确保 data
在没有 undefined
检查的情况下定义。
¥It’s best to check if an error
is present before using the data
property. This allows you to handle errors in advance and ensures data
is defined without an undefined
check.
直接访问 data
而不进行错误检查
Section titled 直接访问 data 而不进行错误检查¥Accessing data
directly without an error check
要跳过错误处理,例如在原型设计或使用将为你捕获错误的库时,请在操作调用中使用 .orThrow()
属性来抛出错误,而不是返回 error
。这将直接返回操作的 data
。
¥To skip error handling, for example while prototyping or using a library that will catch errors for you, use the .orThrow()
property on your action call to throw errors instead of returning an error
. This will return the action’s data
directly.
此示例调用 likePost()
操作,该操作从操作 handler
返回更新的点赞数作为 number
:
¥This example calls a likePost()
action that returns the updated number of likes as a number
from the action handler
:
处理操作中的后端错误
Section titled 处理操作中的后端错误¥Handling backend errors in your action
你可以使用提供的 ActionError
从操作 handler()
中抛出错误,例如当数据库条目丢失时抛出 “未找到”,当用户未登录时抛出 “unauthorized”。与返回 undefined
相比,这有两个主要好处:
¥You can use the provided ActionError
to throw an error from your action handler()
, such as “not found” when a database entry is missing, or “unauthorized” when a user is not logged in. This has two main benefits over returning undefined
:
-
你可以设置状态代码,如
404 - Not found
或401 - Unauthorized
。通过让你查看每个请求的状态代码,可以改善开发和生产中的错误调试。 -
在你的应用代码中,所有错误都会传递给操作结果上的
error
对象。这避免了对数据进行undefined
检查的需要,并允许你根据出现的问题向用户显示有针对性的反馈。
创建 ActionError
Section titled 创建 ActionError¥Creating an ActionError
要抛出错误,请从 astro:actions
模块导入 ActionError()
类。向其传递一个人类可读的状态 code
(例如 "NOT_FOUND"
或 "BAD_REQUEST"
)和一个可选的 message
以提供有关错误的更多信息。
¥To throw an error, import the ActionError()
class from the astro:actions
module. Pass it a human-readable status code
(e.g. "NOT_FOUND"
or "BAD_REQUEST"
), and an optional message
to provide further information about the error.
此示例在用户未登录时从 likePost
操作抛出错误,在检查假设的 “user-session” cookie 进行身份验证后:
¥This example throws an error from a likePost
action when a user is not logged in, after checking a hypothetical “user-session” cookie for authentication:
处理 ActionError
Section titled 处理 ActionError¥Handling an ActionError
要处理此错误,你可以从应用调用操作并检查是否存在 error
属性。此属性将为 ActionError
类型,并将包含你的 code
和 message
。
¥To handle this error, you can call the action from your application and check whether an error
property is present. This property will be of type ActionError
and will contain your code
and message
.
在下面的示例中,LikeButton.tsx
组件在被点击时会调用 likePost()
操作。如果发生身份验证错误,则使用 error.code
属性来确定是否显示登录链接:
¥In the following example, a LikeButton.tsx
component calls the likePost()
action when clicked. If an authentication error occurs, the error.code
attribute is used to determine whether to display a login link:
处理客户端重定向
Section titled 处理客户端重定向¥Handling client redirects
从客户端调用操作时,你可以与客户端库(如 react-router
)集成,或者使用 Astro 的 navigate()
功能 在操作成功时重定向到新页面。
¥When calling actions from the client, you can integrate with a client-side library like react-router
, or you can use Astro’s navigate()
function to redirect to a new page when an action succeeds.
此示例在 logout
操作成功返回后导航到主页:
¥This example navigates to the homepage after a logout
action returns successfully:
从操作中接受表单数据
Section titled 从操作中接受表单数据¥Accepting form data from an action
操作默认接受 JSON 数据。要从 HTML 表单接受表单数据,请在 defineAction()
调用中设置 accept: 'form'
:
¥Actions accept JSON data by default. To accept form data from an HTML form, set accept: 'form'
in your defineAction()
call:
验证表单数据
Section titled 验证表单数据¥Validating form data
操作将使用每个输入的 name
属性的值作为对象键,将提交的表单数据解析为对象。例如,包含 <input name="search">
的表单将被解析为像 { search: 'user input' }
这样的对象。你的操作的 input
架构将用于验证此对象。
¥Actions will parse submitted form data to an object, using the value of each input’s name
attribute as the object keys. For example, a form containing <input name="search">
will be parsed to an object like { search: 'user input' }
. Your action’s input
schema will be used to validate this object.
要在操作处理程序中接收原始 FormData
对象而不是解析的对象,请在操作定义中省略 input
属性。
¥To receive the raw FormData
object in your action handler instead of a parsed object, omit the input
property in your action definition.
以下示例显示经过验证的新闻稿注册表单,该表单接受用户的电子邮件并需要 “服务条款” 同意复选框。
¥The following example shows a validated newsletter registration form that accepts a user’s email and requires a “terms of service” agreement checkbox.
-
Create an HTML form component with unique
name
attributes on each input: -
Define a
newsletter
action to handle the submitted form. Validate theemail
field using thez.string().email()
validator, and theterms
checkbox usingz.boolean()
:See theinput
API reference for all available form validators. -
Add a
<script>
to the HTML form to submit the user input. This example overrides the form’s default submit behavior to callactions.newsletter()
, and redirects to/confirmation
using thenavigate()
function:See “Call actions from an HTML form action” for an alternative way to submit form data.
显示表单输入错误
Section titled 显示表单输入错误¥Displaying form input errors
你可以使用 原生 HTML 表单验证属性(如 required
、type="email"
和 pattern
)在提交之前验证表单输入。对于后端更复杂的 input
验证,你可以使用提供的 isInputError()
实用函数。
¥You can validate form inputs before submission using native HTML form validation attributes like required
, type="email"
, and pattern
. For more complex input
validation on the backend, you can use the provided isInputError()
utility function.
要检索输入错误,请使用 isInputError()
实用程序检查错误是否由无效输入引起。输入错误包含一个 fields
对象,其中包含每个无法验证的输入名称的消息。你可以使用这些消息提示用户更正其提交。
¥To retrieve input errors, use the isInputError()
utility to check whether an error was caused by invalid input. Input errors contain a fields
object with messages for each input name that failed to validate. You can use these messages to prompt your user to correct their submission.
以下示例使用 isInputError()
检查错误,然后检查错误是否在电子邮件字段中,最后根据错误创建消息。你可以使用 JavaScript DOM 操作或你喜欢的 UI 框架向用户显示此消息。
¥The following example checks the error with isInputError()
, then checks whether the error is in the email field, before finally creating a message from the errors. You can use JavaScript DOM manipulation or your preferred UI framework to display this message to users.
从 HTML 表单操作调用操作
Section titled 从 HTML 表单操作调用操作¥Call actions from an HTML form action
你可以使用任何 <form>
元素上的标准属性启用零 JS 表单提交。没有客户端 JavaScript 的表单提交可能既可以作为 JavaScript 加载失败时的后备,也可以作为你更喜欢完全从服务器处理表单时的后备。
¥You can enable zero-JS form submissions with standard attributes on any <form>
element. Form submissions without client-side JavaScript may be useful both as a fallback for when JavaScript fails to load, or if you prefer to handle forms entirely from the server.
在服务器上调用 Astro.getActionResult() 会返回表单提交的结果(data
或 error
),并可用于动态重定向、处理表单错误、更新 UI 等。
¥Calling Astro.getActionResult() on the server returns the result of your form submission (data
or error
), and can be used to dynamically redirect, handle form errors, update the UI, and more.
要从 HTML 表单调用操作,请将 method="POST"
添加到 <form>
,然后使用你的操作设置表单的 action
属性,例如 action={actions.logout}
。这将设置 action
属性以使用由服务器自动处理的查询字符串。
¥To call an action from an HTML form, add method="POST"
to your <form>
, then set the form’s action
attribute using your action, for example action={actions.logout}
. This will set the action
attribute to use a query string that is handled by the server automatically.
例如,此 Astro 组件在单击按钮时调用 logout
操作并重新加载当前页面:
¥For example, this Astro component calls the logout
action when the button is clicked and reloads the current page:
操作成功时重定向
Section titled 操作成功时重定向¥Redirect on action success
要在没有客户端 JavaScript 的情况下在操作成功时导航到其他页面,你可以在 action
属性中添加路径。
¥To navigate to a different page when an action is successful without client-side JavaScript, you can prepend a path in the action
attribute.
例如,当 newsletter
操作成功时,action={'/confirmation' + actions.newsletter}
将导航到 /confirmation
:
¥For example, action={'/confirmation' + actions.newsletter}
will navigate to /confirmation
when the newsletter
action succeeds:
操作成功时动态重定向
Section titled 操作成功时动态重定向¥Dynamic redirect on action success
如果你需要动态决定重定向到哪里,你可以使用服务器上的操作结果。一个常见示例是创建产品记录并重定向到新产品的页面,例如 /products/[id]
。
¥If you need to decide where to redirect to dynamically, you can use an action’s result on the server. A common example is creating a product record and redirecting to the new product’s page, e.g. /products/[id]
.
例如,假设你有一个 createProduct
操作,该操作返回生成的产品 ID:
¥For example, say you have a createProduct
action that returns the generated product id:
你可以通过调用 Astro.getActionResult()
从 Astro 组件中检索操作结果。当调用操作时,这将返回一个包含 data
或 error
属性的对象,如果在此请求期间未调用该操作,则返回 undefined
。
¥You can retrieve the action result from your Astro component by calling Astro.getActionResult()
. This returns an object containing data
or error
properties when an action is called, or undefined
if the action was not called during this request.
使用 data
属性构造与 Astro.redirect()
一起使用的 URL:
¥Use the data
property to construct a URL to use with Astro.redirect()
:
处理表单操作错误
Section titled 处理表单操作错误¥Handle form action errors
当操作失败时,Astro 不会重定向到你的 action
路由。相反,当前页面会重新加载操作返回的任何错误。在包含表单的 Astro 组件中调用 Astro.getActionResult()
可让你访问 error
对象以进行自定义错误处理。
¥Astro will not redirect to your action
route when an action fails. Instead, the current page is reloaded with any errors the action returned. Calling Astro.getActionResult()
in the Astro component containing your form gives you access to the error
object for custom error handling.
以下示例在 newsletter
操作失败时显示一般失败消息:
¥The following example displays a general failure message when a newsletter
action fails:
如需更多自定义,你可以使用 使用 isInputError()
实用程序 检查错误是否由无效输入引起。
¥For more customization, you can use the isInputError()
utility to check whether an error is caused by invalid input.
以下示例在提交无效电子邮件时在 email
输入字段下渲染错误横幅:
¥The following example renders an error banner under the email
input field when an invalid email is submitted:
发生错误时保留输入值
Section titled 发生错误时保留输入值¥Preserve input values on error
每当提交表单时,输入都会被清除。要保留输入值,你可以在页面上 启用视图转换 并将 transition:persist
指令应用于每个输入:
¥Inputs will be cleared whenever a form is submitted. To persist input values, you can enable view transitions on the page and apply the transition:persist
directive to each input:
使用表单操作结果更新 UI
Section titled 使用表单操作结果更新 UI¥Update the UI with a form action result
Astro.getActionResult()
返回的结果是一次性的,并且每当页面刷新时都会重置为 undefined
。这对于 显示输入错误 来说是理想的,并且在成功时向用户显示临时通知。
¥The result returned by Astro.getActionResult()
is single-use, and will reset to undefined
whenever the page is refreshed. This is ideal for displaying input errors and showing temporary notifications to the user on success.
将操作传递给 Astro.getActionResult()
并使用返回的 data
属性来渲染你想要显示的任何临时 UI。此示例使用 addToCart
操作返回的 productName
属性显示成功消息:
¥Pass an action to Astro.getActionResult()
and use the returned data
property to render any temporary UI you want to display. This example uses the productName
property returned by an addToCart
action to show a success message: