API 参考
Astro
全局
Section titled Astro 全局¥Astro
global
Astro
全局在 .astro
文件的所有上下文中都可用。它具有以下功能:
¥The Astro
global is available in all contexts in .astro
files. It has the following functions:
Astro.glob()
Section titled Astro.glob()Astro.glob()
是一种将许多本地文件加载到静态站点设置中的方法。
¥Astro.glob()
is a way to load many local files into your static site setup.
.glob()
仅采用一个参数:你要导入的本地文件的相对 URL 全局。它是异步的,并返回匹配文件的导出数组。
¥.glob()
only takes one parameter: a relative URL glob of which local files you’d like to import. It’s asynchronous, and returns an array of the exports from matching files.
.glob()
不能接受变量或插入它们的字符串,因为它们不可静态分析。(请参阅 the troubleshooting guide for a workaround.) This is because Astro.glob()
is a wrapper of Vite’s import.meta.glob()
。
¥.glob()
can’t take variables or strings that interpolate them, as they aren’t statically analyzable. (See the troubleshooting guide for a workaround.) This is because Astro.glob()
is a wrapper of Vite’s import.meta.glob()
.
Markdown 文件
Section titled Markdown 文件¥Markdown Files
使用 Astro.glob()
加载的 Markdown 文件返回以下 MarkdownInstance
接口:
¥Markdown files loaded with Astro.glob()
return the following MarkdownInstance
interface:
你可以选择使用 TypeScript 泛型为 frontmatter
变量提供类型。
¥You can optionally provide a type for the frontmatter
variable using a TypeScript generic.
Astro 档案
Section titled Astro 档案¥Astro Files
Astro 文件具有以下接口:
¥Astro files have the following interface:
¥Other Files
其他文件可能有各种不同的接口,但如果你确切知道无法识别的文件类型包含什么内容,Astro.glob()
就会接受 TypeScript 泛型。
¥Other files may have various different interfaces, but Astro.glob()
accepts a TypeScript generic if you know exactly what an unrecognized file type contains.
Astro.props
Section titled Astro.propsAstro.props
是一个对象,包含已作为 组件属性 传递的任何值。.md
和 .mdx
文件的布局组件接收 frontmatter 值作为 props。
¥Astro.props
is an object containing any values that have been passed as component attributes. Layout components for .md
and .mdx
files receive frontmatter values as props.
Astro.params
Section titled Astro.paramsAstro.params
是一个对象,包含与该请求匹配的动态路由段的值。
¥Astro.params
is an object containing the values of dynamic route segments matched for this request.
在静态构建中,这将是 getStaticPaths()
返回的 params
,用于预渲染 动态路由。
¥In static builds, this will be the params
returned by getStaticPaths()
used for prerendering dynamic routes.
在 SSR 构建中,这可以是与动态路由模式中的路径段匹配的任何值。
¥In SSR builds, this can be any value matching the path segments in the dynamic route pattern.
也可以看看:params
¥See also: params
Astro.request
Section titled Astro.request类型:Request
¥Type: Request
Astro.request
是标准 要求 对象。它可用于获取 url
、headers
、method
,甚至请求的正文。
¥Astro.request
is a standard Request object. It can be used to get the url
, headers
, method
, and even body of the request.
也可以看看:Astro.url
¥See also: Astro.url
Astro.response
Section titled Astro.response类型:ResponseInit & { readonly headers: Headers }
¥Type: ResponseInit & { readonly headers: Headers }
Astro.response
是标准 ResponseInit
对象。它具有以下结构。
¥Astro.response
is a standard ResponseInit
object. It has the following structure.
-
status
:响应的数字状态代码,例如200
。 -
statusText
:与状态代码关联的状态消息,例如'OK'
。 -
headers
:可用于设置响应的 HTTP 标头的Headers
实例。
Astro.response
用于设置页面响应的 status
、statusText
和 headers
。
¥Astro.response
is used to set the status
, statusText
, and headers
for a page’s response.
或者设置标题:
¥Or to set a header:
Astro.cookies
Section titled Astro.cookies类型:AstroCookies
¥Type: AstroCookies
astro@1.4.0
Astro.cookies
包含用于在 服务器端渲染 模式下读取和操作 cookie 的实用程序。
¥Astro.cookies
contains utilities for reading and manipulating cookies in server-side rendering mode.
类型:(key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined
¥Type: (key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined
获取 cookie 作为 AstroCookie
对象,其中包含 value
和用于将 cookie 转换为非字符串类型的实用函数。
¥Gets the cookie as an AstroCookie
object, which contains the value
and utility functions for converting the cookie to non-string types.
类型:(key: string, options?: AstroCookieGetOptions) => boolean
¥Type: (key: string, options?: AstroCookieGetOptions) => boolean
该 cookie 是否存在。如果 cookie 已通过 Astro.cookies.set()
设置,则返回 true,否则将检查 Astro.request
中的 cookie。
¥Whether this cookie exists. If the cookie has been set via Astro.cookies.set()
this will return true, otherwise it will check cookies in the Astro.request
.
类型:(key: string, value: string | object, options?: AstroCookieSetOptions) => void
¥Type: (key: string, value: string | object, options?: AstroCookieSetOptions) => void
将 cookie key
设置为给定值。这将尝试将 cookie 值转换为字符串。选项提供了设置 cookie 功能 的方法,例如 maxAge
或 httpOnly
。
¥Sets the cookie key
to the given value. This will attempt to convert the cookie value to a string. Options provide ways to set cookie features, such as the maxAge
or httpOnly
.
delete
Section titled delete类型:(key: string, options?: AstroCookieDeleteOptions) => void
¥Type: (key: string, options?: AstroCookieDeleteOptions) => void
通过将到期日期设置为过去(Unix 时间为 0)来使 cookie 无效。
¥Invalidates a cookie by setting the expiration date in the past (0 in Unix time).
一旦 cookie 为 “deleted”(已过期),Astro.cookies.has()
将返回 false
,而 Astro.cookies.get()
将返回 AstroCookie
,value
为 undefined
。删除 cookie 时可用的选项是:domain
、path
、httpOnly
、sameSite
和 secure
。
¥Once a cookie is “deleted” (expired), Astro.cookies.has()
will return false
and Astro.cookies.get()
will return an AstroCookie
with a value
of undefined
. Options available when deleting a cookie are: domain
, path
, httpOnly
, sameSite
, and secure
.
merge
Section titled merge类型:(cookies: AstroCookies) => void
¥Type: (cookies: AstroCookies) => void
将新的 AstroCookies
实例合并到当前实例中。任何新的 cookie 都将添加到当前实例,任何具有相同名称的 cookie 都将覆盖现有值。
¥Merges a new AstroCookies
instance into the current instance. Any new cookies will be added to the current instance and any cookies with the same name will overwrite existing values.
headers
Section titled headers类型:() => Iterator<string>
¥Type: () => Iterator<string>
获取将与响应一起发送的 Set-Cookie
标头值。
¥Gets the header values for Set-Cookie
that will be sent out with the response.
AstroCookie
Section titled AstroCookie通过 Astro.cookies.get()
获取 cookie 返回 AstroCookie
类型。它具有以下结构。
¥Getting a cookie via Astro.cookies.get()
returns a AstroCookie
type. It has the following structure.
value
Section titled value类型:string
¥Type: string
cookie 的原始字符串值。
¥The raw string value of the cookie.
类型:() => Record<string, any>
¥Type: () => Record<string, any>
通过 JSON.parse()
解析 cookie 值,返回一个对象。如果 cookie 值不是有效的 JSON,则抛出此错误。
¥Parses the cookie value via JSON.parse()
, returning an object. Throws if the cookie value is not valid JSON.
number
Section titled number类型:() => number
¥Type: () => number
将 cookie 值解析为数字。如果不是有效数字,则返回 NaN。
¥Parses the cookie value as a Number. Returns NaN if not a valid number.
boolean
Section titled boolean类型:() => boolean
¥Type: () => boolean
将 cookie 值转换为布尔值。
¥Converts the cookie value to a boolean.
AstroCookieGetOptions
Section titled AstroCookieGetOptions
Added in:
astro@4.1.0
获取 cookie 还允许通过 AstroCookieGetOptions
接口指定选项:
¥Getting a cookie also allows specifying options via the AstroCookieGetOptions
interface:
decode
Section titled decode类型:(value: string) => string
¥Type: (value: string) => string
允许自定义如何将 cookie 反序列化为值。
¥Allows customization of how a cookie is deserialized into a value.
AstroCookieSetOptions
Section titled AstroCookieSetOptions
Added in:
astro@4.1.0
通过 Astro.cookies.set()
设置 cookie 允许传入 AstroCookieSetOptions
以自定义 cookie 的序列化方式。
¥Setting a cookie via Astro.cookies.set()
allows passing in a AstroCookieSetOptions
to customize how the cookie is serialized.
domain
Section titled domain类型:string
¥Type: string
指定域。如果未设置域,大多数客户端将解释为应用于当前域。
¥Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.
expires
Section titled expires类型:Date
¥Type: Date
指定 cookie 过期的日期。
¥Specifies the date on which the cookie will expire.
httpOnly
Section titled httpOnly类型:boolean
¥Type: boolean
如果为 true,则 cookie 将无法在客户端访问。
¥If true, the cookie will not be accessible client-side.
maxAge
Section titled maxAge类型:number
¥Type: number
指定 cookie 有效的数字(以秒为单位)。
¥Specifies a number, in seconds, for which the cookie is valid.
类型:string
¥Type: string
指定应用 cookie 的域的子路径。
¥Specifies a subpath of the domain in which the cookie is applied.
sameSite
Section titled sameSite类型:boolean | 'lax' | 'none' | 'strict'
¥Type: boolean | 'lax' | 'none' | 'strict'
指定 SameSite cookie 标头的值。
¥Specifies the value of the SameSite cookie header.
secure
Section titled secure类型:boolean
¥Type: boolean
如果为 true,则 cookie 仅在 https 站点上设置。
¥If true, the cookie is only set on https sites.
encode
Section titled encode类型:(value: string) => string
¥Type: (value: string) => string
允许自定义如何序列化 cookie。
¥Allows customizing how the cookie is serialized.
Astro.redirect()
Section titled Astro.redirect()类型:(path: string, status?: number) => Response
¥Type: (path: string, status?: number) => Response
允许你重定向到另一个页面,并可选择提供 HTTP 响应状态代码 作为第二个参数。
¥Allows you to redirect to another page, and optionally provide an HTTP response status code as a second parameter.
页面(而不是子组件)必须 return
为 Astro.redirect()
的结果才能发生重定向。
¥A page (and not a child component) must return
the result of Astro.redirect()
for the redirect to occur.
对于静态生成的站点,这将使用 <meta http-equiv="refresh">
标签 生成客户端重定向,并且不支持状态代码。
¥For statically-generated sites, this will produce a client redirect using a <meta http-equiv="refresh">
tag and does not support status codes.
使用按需渲染模式时,支持状态代码。除非指定其他代码,否则 Astro 将以默认 HTTP 响应状态 302
提供重定向请求。
¥When using an on-demand rendering mode, status codes are supported. Astro will serve redirected requests with a default HTTP response status of 302
unless another code is specified.
以下示例将用户重定向到登录页面:
¥The following example redirects a user to a login page:
Astro.rewrite()
Section titled Astro.rewrite()类型:(rewritePayload: string | URL | Request) => Promise<Response>
¥Type: (rewritePayload: string | URL | Request) => Promise<Response>
astro@4.13.0
允许你从不同的 URL 或路径提供内容,而无需将浏览器重定向到新页面。
¥Allows you to serve content from a different URL or path without redirecting the browser to a new page.
该方法接受字符串、URL
或 Request
作为路径的位置。
¥The method accepts either a string, a URL
, or a Request
for the location of the path.
使用字符串提供显式路径:
¥Use a string to provide an explicit path:
当你需要构建重写的 URL 路径时,请使用 URL
类型。以下示例通过从相对 "../"
路径创建新的 URL 来渲染页面的父路径:
¥Use a URL
type when you need to construct the URL path for the rewrite. The following example renders a page’s parent path by creating a new URL from the relative "../"
path:
使用 Request
类型完全控制发送到服务器的新路径的 Request
。以下示例发送请求以渲染父页面,同时提供标头:
¥Use a Request
type for complete control of the Request
sent to the server for the new path. The following example sends a request to render the parent page while also providing headers:
Astro.url
Section titled Astro.url类型:URL
¥Type: URL
astro@1.0.0-rc
从当前 Astro.request.url
URL 字符串值构造的 URL 对象。对于与请求 URL 的各个属性(例如路径名和来源)进行交互非常有用。
¥A URL object constructed from the current Astro.request.url
URL string value. Useful for interacting with individual properties of the request URL, like pathname and origin.
相当于做 new URL(Astro.request.url)
。
¥Equivalent to doing new URL(Astro.request.url)
.
如果未为静态站点配置 site,则 Astro.url
将处于开发模式,并且对于使用 server
或 hybrid
输出的按需渲染站点也是如此。
¥Astro.url
will be localhost
in dev mode if site is not configured for static sites, and for on-demand rendered sites using server
or hybrid
output.
你还可以使用 Astro.url
通过将其作为参数传递给 new URL()
来创建新的 URL。
¥You can also use Astro.url
to create new URLs by passing it as an argument to new URL()
.
Astro.clientAddress
Section titled Astro.clientAddress类型:string
¥Type: string
astro@1.0.0-rc
指定请求的 IP 地址。此属性仅在构建 SSR(服务器端渲染)时可用,并且不应用于静态站点。
¥Specifies the IP address of the request. This property is only available when building for SSR (server-side rendering) and should not be used for static sites.
Astro.site
Section titled Astro.site类型:URL | undefined
¥Type: URL | undefined
Astro.site
返回由 Astro 配置中的 site
组成的 URL
。如果 Astro 配置中的 site
未定义,则 Astro.site
将不会被定义。
¥Astro.site
returns a URL
made from site
in your Astro config. If site
in your Astro config isn’t defined, Astro.site
won’t be defined.
Astro.generator
Section titled Astro.generator类型:string
¥Type: string
astro@1.0.0
Astro.generator
是在当前版本的 Astro 中添加 <meta name="generator">
标签的便捷方法。它遵循格式 "Astro v1.x.x"
。
¥Astro.generator
is a convenient way to add a <meta name="generator">
tag with your current version of Astro. It follows the format "Astro v1.x.x"
.
Astro.slots
Section titled Astro.slotsAstro.slots
包含用于修改 Astro 组件的带槽子组件的实用函数。
¥Astro.slots
contains utility functions for modifying an Astro component’s slotted children.
Astro.slots.has()
Section titled Astro.slots.has()类型:(slotName: string) => boolean
¥Type: (slotName: string) => boolean
你可以通过 Astro.slots.has()
检查特定插槽名称的内容是否存在。当你想要封装槽内容,但只想在使用槽时渲染封装器元素时,这可能很有用。
¥You can check whether content for a specific slot name exists with Astro.slots.has()
. This can be useful when you want to wrap slot contents, but only want to render the wrapper elements when the slot is being used.
Astro.slots.render()
Section titled Astro.slots.render()类型:(slotName: string, args?: any[]) => Promise<string>
¥Type: (slotName: string, args?: any[]) => Promise<string>
你可以使用 Astro.slots.render()
将槽的内容异步渲染为 HTML 字符串。
¥You can asynchronously render the contents of a slot to a string of HTML using Astro.slots.render()
.
Astro.slots.render()
可选择接受第二个参数:将转发给任何子函数的参数数组。这对于自定义实用程序组件非常有用。
¥Astro.slots.render()
optionally accepts a second argument: an array of parameters that will be forwarded to any function children. This can be useful for custom utility components.
例如,这个 <Shout />
组件将其 message
属性转换为大写并将其传递到默认插槽:
¥For example, this <Shout />
component converts its message
prop to uppercase and passes it to the default slot:
作为 <Shout />
子级传递的回调函数将接收全大写的 message
参数:
¥A callback function passed as <Shout />
’s child will receive the all-caps message
parameter:
回调函数可以传递给带有 slot
属性的封装 HTML 元素标记内的命名插槽。此元素仅用于将回调传输到命名插槽,不会渲染到页面上。
¥Callback functions can be passed to named slots inside a wrapping HTML element tag with a slot
attribute. This element is only used to transfer the callback to a named slot and will not be rendered onto the page.
使用标准 HTML 元素作为封装标签,或任何不会被解释为组件的小写标签(例如 <fragment>
而不是 <Fragment />
)。请勿使用 HTML <slot>
元素,因为这将被解释为 Astro 插槽。
¥Use a standard HTML element for the wrapping tag, or any lower case tag (e.g. <fragment>
instead of <Fragment />
) that will not be interpreted as a component. Do not use the HTML <slot>
element as this will be interpreted as an Astro slot.
Astro.self
Section titled Astro.selfAstro.self
允许递归调用 Astro 组件。此行为允许你通过在组件模板中使用 <Astro.self>
从其内部渲染 Astro 组件。这对于迭代大型数据存储和嵌套数据结构很有帮助。
¥Astro.self
allows Astro components to be recursively called. This behaviour lets you render an Astro component from within itself by using <Astro.self>
in the component template. This can be helpful for iterating over large data stores and nested data-structures.
然后可以像这样使用该组件:
¥This component could then be used like this:
并且会像这样渲染 HTML:
¥And would render HTML like this:
Astro.locals
Section titled Astro.locals
Added in:
astro@2.4.0
Astro.locals
是一个对象,包含来自中间件的 context.locals
对象的任何值。使用它来访问 .astro
文件中中间件返回的数据。
¥Astro.locals
is an object containing any values from the context.locals
object from a middleware. Use this to access data returned by middleware in your .astro
files.
Astro.preferredLocale
Section titled Astro.preferredLocale类型:string | undefined
¥Type: string | undefined
astro@3.5.0
Astro.preferredLocale
是一个计算值,表示用户的首选区域设置。
¥Astro.preferredLocale
is a computed value that represents the preferred locale of the user.
它是通过检查 i18n.locales
数组中配置的区域设置以及用户浏览器通过标头 Accept-Language
支持的区域设置来计算的。如果不存在此类匹配,则该值为 undefined
。
¥It is computed by checking the configured locales in your i18n.locales
array and locales supported by the users’s browser via the header Accept-Language
. This value is undefined
if no such match exists.
此属性仅在构建 SSR(服务器端渲染)时可用,并且不应用于静态站点。
¥This property is only available when building for SSR (server-side rendering) and should not be used for static sites.
Astro.preferredLocaleList
Section titled Astro.preferredLocaleList类型:string[] | undefined
¥Type: string[] | undefined
astro@3.5.0
Astro.preferredLocaleList
代表浏览器请求且你的网站支持的所有区域设置的数组。这会生成你的网站和访问者之间所有兼容语言的列表。
¥Astro.preferredLocaleList
represents the array of all locales that are both requested by the browser and supported by your website. This produces a list of all compatible languages between your site and your visitor.
如果在你的区域设置数组中找不到浏览器请求的语言,则该值为 []
:你不支持访问者的任何首选区域设置。
¥If none of the browser’s requested languages are found in your locales array, then the value is []
: you do not support any of your visitor’s preferred locales.
如果浏览器没有指定任何首选语言,则该值将为 i18n.locales
:你支持的所有区域设置都将被无偏好的访问者视为同等偏好。
¥If the browser does not specify any preferred languages, then this value will be i18n.locales
: all of your supported locales will be considered equally preferred by a visitor with no preferences.
此属性仅在构建 SSR(服务器端渲染)时可用,并且不应用于静态站点。
¥This property is only available when building for SSR (server-side rendering) and should not be used for static sites.
Astro.currentLocale
Section titled Astro.currentLocale类型:string | undefined
¥Type: string | undefined
astro@3.5.6
使用 locales
配置中指定的语法从当前 URL 计算出的区域设置。如果 URL 不包含 /[locale]/
前缀,则该值将默认为 i18n.defaultLocale
。
¥The locale computed from the current URL, using the syntax specified in your locales
configuration. If the URL does not contain a /[locale]/
prefix, then the value will default to i18n.defaultLocale
.
Astro.getActionResult()
Section titled Astro.getActionResult()类型:(action: TAction) => ActionReturnType<TAction> | undefined
¥Type: (action: TAction) => ActionReturnType<TAction> | undefined
astro@4.15.0
Astro.getActionResult()
是一个返回 操作 提交结果的函数。这接受一个操作函数作为参数(例如 actions.logout
),并在收到提交时返回 data
或 error
对象。否则,它将返回 undefined
。
¥Astro.getActionResult()
is a function that returns the result of an Action submission. This accepts an action function as an argument (e.g. actions.logout
) and returns a data
or error
object when a submission is received. Otherwise, it will return undefined
.
Astro.callAction()
Section titled Astro.callAction()
Added in:
astro@4.15.0
Astro.callAction()
是一个用于直接从 Astro 组件调用操作处理程序的函数。此函数接受 Action 函数作为第一个参数(例如 actions.logout
),并接受该操作接收的任何输入作为第二个参数。它将操作的结果作为 promise 返回。
¥Astro.callAction()
is a function used to call an Action handler directly from your Astro component. This function accepts an Action function as the first argument (e.g. actions.logout
) and any input that action receives as the second argument. It returns the result of the action as a promise.
端点上下文
Section titled 端点上下文¥Endpoint Context
端点功能 接收上下文对象作为第一个参数。它反映了 Astro
的许多全局属性。
¥Endpoint functions receive a context object as the first parameter. It mirrors many of the Astro
global properties.
context.params
Section titled context.paramscontext.params
是一个对象,包含与该请求匹配的动态路由段的值。
¥context.params
is an object containing the values of dynamic route segments matched for this request.
在静态构建中,这将是 getStaticPaths()
返回的 params
,用于预渲染 动态路由。
¥In static builds, this will be the params
returned by getStaticPaths()
used for prerendering dynamic routes.
在 SSR 构建中,这可以是与动态路由模式中的路径段匹配的任何值。
¥In SSR builds, this can be any value matching the path segments in the dynamic route pattern.
也可以看看:params
¥See also: params
context.props
Section titled context.props
Added in:
astro@1.5.0
context.props
是一个包含从 getStaticPaths()
传递的任何 props
的对象。由于在构建 SSR(服务器端渲染)时不使用 getStaticPaths()
,因此 context.props
仅在静态构建中可用。
¥context.props
is an object containing any props
passed from getStaticPaths()
. Because getStaticPaths()
is not used when building for SSR (server-side rendering), context.props
is only available in static builds.
也可以看看:使用 props
传递数据
¥See also: Data Passing with props
context.request
Section titled context.request类型:Request
¥Type: Request
标准 要求 对象。它可用于获取 url
、headers
、method
,甚至请求的正文。
¥A standard Request object. It can be used to get the url
, headers
, method
, and even body of the request.
也可以看看:Astro.request
¥See also: Astro.request
context.cookies
Section titled context.cookies类型:AstroCookies
¥Type: AstroCookies
context.cookies
包含用于读取和操作 cookie 的实用程序。
¥context.cookies
contains utilities for reading and manipulating cookies.
也可以看看:Astro.cookies
¥See also: Astro.cookies
context.url
Section titled context.url类型:URL
¥Type: URL
astro@1.5.0
从当前 context.request.url
URL 字符串值构造的 URL 对象。
¥A URL object constructed from the current context.request.url
URL string value.
也可以看看:Astro.url
¥See also: Astro.url
context.clientAddress
Section titled context.clientAddress类型:string
¥Type: string
astro@1.5.0
指定请求的 IP 地址。此属性仅在构建 SSR(服务器端渲染)时可用,并且不应用于静态站点。
¥Specifies the IP address of the request. This property is only available when building for SSR (server-side rendering) and should not be used for static sites.
也可以看看:Astro.clientAddress
¥See also: Astro.clientAddress
context.site
Section titled context.site类型:URL | undefined
¥Type: URL | undefined
astro@1.5.0
context.site
返回由 Astro 配置中的 site
组成的 URL
。如果未定义,这将返回从 localhost
生成的 URL。
¥context.site
returns a URL
made from site
in your Astro config. If undefined, this will return a URL generated from localhost
.
也可以看看:Astro.site
¥See also: Astro.site
context.generator
Section titled context.generator类型:string
¥Type: string
astro@1.5.0
context.generator
是指示项目正在运行的 Astro 版本的便捷方法。它遵循格式 "Astro v1.x.x"
。
¥context.generator
is a convenient way to indicate the version of Astro your project is running. It follows the format "Astro v1.x.x"
.
也可以看看:Astro.generator
¥See also: Astro.generator
context.redirect()
Section titled context.redirect()类型:(path: string, status?: number) => Response
¥Type: (path: string, status?: number) => Response
astro@1.5.0
context.redirect()
返回一个 响应 对象,允许你重定向到另一个页面。此功能仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。
¥context.redirect()
returns a Response object that allows you to redirect to another page. This function is only available when building for SSR (server-side rendering) and should not be used for static sites.
也可以看看:Astro.redirect()
¥See also: Astro.redirect()
context.rewrite()
Section titled context.rewrite()类型:(rewritePayload: string | URL | Request) => Promise<Response>
¥Type: (rewritePayload: string | URL | Request) => Promise<Response>
astro@4.13.0
允许你从不同的 URL 或路径提供内容,而无需将浏览器重定向到新页面。
¥Allows you to serve content from a different URL or path without redirecting the browser to a new page.
该方法接受字符串、URL
或 Request
作为路径的位置。
¥The method accepts either a string, a URL
, or a Request
for the location of the path.
使用字符串提供显式路径:
¥Use a string to provide an explicit path:
当你需要构建重写的 URL 路径时,请使用 URL
类型。以下示例通过从相对 "../"
路径创建新的 URL 来渲染页面的父路径:
¥Use a URL
type when you need to construct the URL path for the rewrite. The following example renders a page’s parent path by creating a new URL from the relative "../"
path:
使用 Request
类型完全控制发送到服务器的新路径的 Request
。以下示例发送请求以渲染父页面,同时提供标头:
¥Use a Request
type for complete control of the Request
sent to the server for the new path. The following example sends a request to render the parent page while also providing headers:
也可以看看:Astro.rewrite()
¥See also: Astro.rewrite()
context.locals
Section titled context.locals
Added in:
astro@2.4.0
context.locals
是一个用于在请求生命周期中存储和访问任意信息的对象。
¥context.locals
is an object used to store and access arbitrary information during the lifecycle of a request.
中间件函数可以读取和写入 context.locals
的值:
¥Middleware functions can read and write the values of context.locals
:
API 端点只能从 context.locals
读取信息:
¥API endpoints can only read information from context.locals
:
也可以看看:Astro.locals
¥See also: Astro.locals
context.getActionResult()
Section titled context.getActionResult()类型:(action: TAction) => ActionReturnType<TAction> | undefined
¥Type: (action: TAction) => ActionReturnType<TAction> | undefined
astro@4.15.0
context.getActionResult()
是一个返回 操作 提交结果的函数。这接受一个操作函数作为参数(例如 actions.logout
),并在收到提交时返回 data
或 error
对象。否则,它将返回 undefined
。
¥context.getActionResult()
is a function that returns the result of an Action submission. This accepts an action function as an argument (e.g. actions.logout
), and returns a data
or error
object when a submission is received. Otherwise, it will return undefined
.
¥See also Astro.getActionResult()
context.callAction()
Section titled context.callAction()
Added in:
astro@4.15.0
context.callAction()
是一个用于直接从 Astro 组件调用操作处理程序的函数。此函数接受 Action 函数作为第一个参数(例如 actions.logout
),并接受该操作接收的任何输入作为第二个参数。它将操作的结果作为 promise 返回。
¥context.callAction()
is a function used to call an Action handler directly from your Astro component. This function accepts an Action function as the first argument (e.g. actions.logout
) and any input that action receives as the second argument. It returns the result of the action as a promise.
另请参阅 Astro.callAction()
¥See also Astro.callAction()
getStaticPaths()
Section titled getStaticPaths()类型:(options: GetStaticPathsOptions) => Promise<GetStaticPathsResult> | GetStaticPathsResult
¥Type: (options: GetStaticPathsOptions) => Promise<GetStaticPathsResult> | GetStaticPathsResult
如果页面在文件名中使用动态参数,则该组件将需要导出 getStaticPaths()
函数。
¥If a page uses dynamic params in the filename, that component will need to export a getStaticPaths()
function.
这个函数是必需的,因为 Astro 是一个静态站点构建器。这意味着你的整个网站是提前构建的。如果 Astro 不知道在构建时生成页面,你的用户在访问你的网站时将看不到它。
¥This function is required because Astro is a static site builder. That means that your entire site is built ahead of time. If Astro doesn’t know to generate a page at build time, your users won’t see it when they visit your site.
getStaticPaths()
函数应返回一个对象数组,以确定 Astro 将预渲染哪些路径。
¥The getStaticPaths()
function should return an array of objects to determine which paths will be pre-rendered by Astro.
它还可以用于 动态路由 的静态文件端点。
¥It can also be used in static file endpoints for dynamic routing.
params
Section titled params每个返回对象的 params
键告诉 Astro 要构建哪些路由。返回的参数必须映射回组件文件路径中定义的动态参数和其余参数。
¥The params
key of every returned object tells Astro what routes to build. The returned params must map back to the dynamic parameters and rest parameters defined in your component filepath.
params
被编码到 URL 中,因此仅支持字符串作为值。每个 params
对象的值必须与页面名称中使用的参数匹配。
¥params
are encoded into the URL, so only strings are supported as values. The value for each params
object must match the parameters used in the page name.
例如,假设你有一个位于 src/pages/posts/[id].astro
的页面。如果你从此页面导出 getStaticPaths
并返回以下路径:
¥For example, suppose that you have a page at src/pages/posts/[id].astro
. If you export getStaticPaths
from this page and return the following for paths:
然后 Astro 会在构建时静态生成 posts/1
、posts/2
和 posts/3
。
¥Then Astro will statically generate posts/1
, posts/2
, and posts/3
at build time.
使用 props
传递数据
Section titled 使用 props 传递数据¥Data Passing with props
要将附加数据传递到每个生成的页面,你还可以在每个返回的路径对象上设置 props
值。与 params
不同,props
不会编码到 URL 中,因此不仅限于字符串。
¥To pass additional data to each generated page, you can also set a props
value on every returned path object. Unlike params
, props
are not encoded into the URL and so aren’t limited to only strings.
例如,假设你根据从远程 API 获取的数据生成页面。你可以将完整的数据对象传递给 getStaticPaths
内部的页面组件:
¥For example, suppose that you generate pages based off of data fetched from a remote API. You can pass the full data object to the page component inside of getStaticPaths
:
你还可以传递常规数组,这在生成或存根已知路由列表时可能会有所帮助。
¥You can also pass a regular array, which may be helpful when generating or stubbing a known list of routes.
然后 Astro 将在构建时使用 pages/posts/[id].astro
中的页面组件静态生成 posts/1
和 posts/2
。该页面可以使用 Astro.props
引用此数据:
¥Then Astro will statically generate posts/1
and posts/2
at build time using the page component in pages/posts/[id].astro
. The page can reference this data using Astro.props
:
paginate()
Section titled paginate()分页是 Astro 通过 paginate()
函数原生支持的网站的常见用例。paginate()
将自动生成从 getStaticPaths()
返回的数组,该数组为分页集合的每一页创建一个 URL。页码将作为参数传递,页面数据将作为 page
属性传递。
¥Pagination is a common use-case for websites that Astro natively supports via the paginate()
function. paginate()
will automatically generate the array to return from getStaticPaths()
that creates one URL for every page of the paginated collection. The page number will be passed as a param, and the page data will be passed as a page
prop.
paginate()
有以下参数:
¥paginate()
has the following arguments:
-
data
- 包含传递给paginate()
函数的页面数据的数组 -
options
- 具有以下属性的可选对象:-
pageSize
- 每页显示的项目数(默认为10
) -
params
- 发送用于创建动态路由的附加参数 -
props
- 发送额外的属性以在每个页面上可用
-
paginate()
假定文件名为 [page].astro
或 [...page].astro
。page
参数成为 URL 中的页码:
¥paginate()
assumes a file name of [page].astro
or [...page].astro
. The page
param becomes the page number in your URL:
-
/posts/[page].astro
将生成 URL/posts/1
、/posts/2
、/posts/3
等。 -
/posts/[...page].astro
将生成 URL/posts
、/posts/2
、/posts/3
等。
分页 page
属性
Section titled 分页 page 属性¥The pagination page
prop
类型:Page<TData>
¥Type: Page<TData>
分页会将 page
属性传递给每个渲染的页面,该页面表示分页集合中的单页数据。这包括你已分页的数据 (page.data
) 以及页面的元数据(page.url
、page.start
、page.end
、page.total
等)。此元数据对于 “下一页” 按钮或 “显示第 1-10 条,共 100 条” 消息等内容很有用。
¥Pagination will pass a page
prop to every rendered page that represents a single page of data in the paginated collection. This includes the data that you’ve paginated (page.data
) as well as metadata for the page (page.url
, page.start
, page.end
, page.total
, etc). This metadata is useful for things like a “Next Page” button or a “Showing 1-10 of 100” message.
page.data
Section titled page.data类型:Array<TData>
¥Type: Array<TData>
当前页面的 paginate()
函数返回的数据数组。
¥Array of data returned from the paginate()
function for the current page.
page.start
Section titled page.start类型:number
¥Type: number
当前页面上第一个项目的索引,从 0
开始。(例如,如果是 pageSize: 25
,则第 1 页上的 0
、第 2 页上的 25
等)
¥Index of first item on current page, starting at 0
. (e.g. if pageSize: 25
, this would be 0
on page 1, 25
on page 2, etc.)
page.end
Section titled page.end类型:number
¥Type: number
当前页面上最后一项的索引。
¥Index of last item on current page.
page.size
Section titled page.size类型:number
默认:10
¥Type: number
Default: 10
每页有多少项。
¥How many items per-page.
page.total
Section titled page.total类型:number
¥Type: number
所有页面的项目总数。
¥The total number of items across all pages.
page.currentPage
Section titled page.currentPage类型:number
¥Type: number
当前页码,从 1
开始。
¥The current page number, starting with 1
.
page.lastPage
Section titled page.lastPage类型:number
¥Type: number
总页数。
¥The total number of pages.
page.url.current
Section titled page.url.current类型:string
¥Type: string
获取当前页面的 URL(对规范 URL 有用)。
¥Get the URL of the current page (useful for canonical URLs).
page.url.prev
Section titled page.url.prev类型:string | undefined
¥Type: string | undefined
获取上一页的 URL(如果在第 1 页,则为 undefined
)。如果为 base
设置了值,请将基本路径添加到 URL 的前面。
¥Get the URL of the previous page (will be undefined
if on page 1). If a value is set for base
, prepend the base path to the URL.
page.url.next
Section titled page.url.next类型:string | undefined
¥Type: string | undefined
获取下一页的 URL(如果没有更多页面,则为 undefined
)。如果为 base
设置了值,请将基本路径添加到 URL 的前面。
¥Get the URL of the next page (will be undefined
if no more pages). If a value is set for base
, prepend the base path to the URL.
page.url.first
Section titled page.url.first类型:string | undefined
¥Type: string | undefined
astro@4.12.0
获取第一页的 URL(如果在第 1 页,则为 undefined
)。如果为 base
设置了值,请将基本路径添加到 URL 的前面。
¥Get the URL of the first page (will be undefined
if on page 1). If a value is set for base
, prepend the base path to the URL.
page.url.last
Section titled page.url.last类型:string | undefined
¥Type: string | undefined
astro@4.12.0
获取最后一页的 URL(如果没有更多页面,则为 undefined
)。如果为 base
设置了值,请将基本路径添加到 URL 的前面。
¥Get the URL of the last page (will be undefined
if no more pages). If a value is set for base
, prepend the base path to the URL.
import.meta
Section titled import.meta所有 ESM 模块都包含 import.meta
属性。Astro 添加了 import.meta.env
到 Vite。
¥All ESM modules include a import.meta
property. Astro adds import.meta.env
through Vite.
import.meta.env.SSR
可以用来知道什么时候在服务器上渲染。有时你可能需要不同的逻辑,例如仅应在客户端中渲染的组件:
¥**import.meta.env.SSR
** can be used to know when rendering on the server. Sometimes you might want different logic, like a component that should only be rendered in the client:
图片 (astro:assets
)
Section titled 图片 (astro:assets)¥Images (astro:assets
)
getImage()
Section titled getImage()类型:(options: UnresolvedImageTransform) => Promise<GetImageResult>
¥Type: (options: UnresolvedImageTransform) => Promise<GetImageResult>
getImage()
函数旨在生成要在其他地方使用的图片,而不是直接在 HTML 中使用,例如在 API 路由 中。它还允许你创建自己的自定义 <Image />
组件。
¥The getImage()
function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an API Route. It also allows you to create your own custom <Image />
component.
getImage()
使用 与 Image 组件具有相同的属性 的选项对象(alt
除外)。
¥getImage()
takes an options object with the same properties as the Image component (except alt
).
它返回具有以下类型的对象:
¥It returns an object with the following type:
内容集 (astro:content
)
Section titled 内容集 (astro:content)¥Content Collections (astro:content
)
Added in:
astro@2.0.0
内容集合提供 API 来配置和查询 src/content/
中的 Markdown 或 MDX 文档。有关功能和使用示例,请参阅我们的内容集合指南。
¥Content collections offer APIs to configure and query your Markdown or MDX documents in src/content/
. For features and usage examples, see our content collections guide.
defineCollection()
Section titled defineCollection()类型:(input: CollectionConfig) => CollectionConfig
¥Type: (input: CollectionConfig) => CollectionConfig
defineCollection()
是一个用于在 src/content/config.*
文件中配置集合的实用程序。
¥defineCollection()
is a utility to configure a collection in a src/content/config.*
file.
该函数接受以下属性:
¥This function accepts the following properties:
类型:'content' | 'data'
默认:'content'
¥Type: 'content' | 'data'
Default: 'content'
astro@2.5.0
type
是一个字符串,定义集合中存储的条目的类型:
¥type
is a string that defines the type of entries stored within a collection:
-
'content'
- 适用于 Markdown (.md
)、MDX (.mdx
) 或 Markdoc (.mdoc
) 等内容创作格式 -
'data'
- 适用于 JSON (.json
) 或 YAML (.yaml
) 等纯数据格式
schema
Section titled schema类型:ZodType | (context: SchemaContext) => ZodType
¥Type: ZodType | (context: SchemaContext) => ZodType
schema
是一个可选的 Zod 对象,用于配置集合的文档 frontmatter 的类型和形状。每个值必须使用 Zod 验证器。
¥schema
is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use a Zod validator.
请参阅 Content Collection
指南 例如用法。
¥See the Content Collection
guide for example usage.
reference()
Section titled reference()类型:(collection: string) => ZodEffects<ZodString, { collection, id: string } | { collection, slug: string }>
¥Type: (collection: string) => ZodEffects<ZodString, { collection, id: string } | { collection, slug: string }>
astro@2.5.0
reference()
函数在内容配置中用于定义关系,或 “参考,” 从一个集合到另一个集合。这接受集合名称并验证内容 frontmatter 或数据文件中指定的条目标识符。
¥The reference()
function is used in the content config to define a relationship, or “reference,” from one collection to another. This accepts a collection name and validates the entry identifier(s) specified in your content frontmatter or data file.
此示例定义了博客作者对 authors
集合的引用以及对同一 blog
集合的相关帖子数组:
¥This example defines references from a blog author to the authors
collection and an array of related posts to the same blog
collection:
请参阅 Content Collection
指南 例如用法。
¥See the Content Collection
guide for example usage.
getCollection()
Section titled getCollection()类型:(collection: string, filter?: (entry: CollectionEntry<TCollectionName>) => boolean) => CollectionEntry<TCollectionName>[]
¥Type: (collection: string, filter?: (entry: CollectionEntry<TCollectionName>) => boolean) => CollectionEntry<TCollectionName>[]
getCollection()
是按集合名称检索内容集合条目列表的函数。
¥getCollection()
is a function that retrieves a list of content collection entries by collection name.
它默认返回集合中的所有项目,并接受可选的 filter
函数以按条目属性缩小范围。这允许你通过 data
对象基于 id
、slug
或 frontmatter 值仅查询集合中的某些项目。
¥It returns all items in the collection by default, and accepts an optional filter
function to narrow by entry properties. This allows you to query for only some items in a collection based on id
, slug
, or frontmatter values via the data
object.
请参阅 Content Collection
指南 例如用法。
¥See the Content Collection
guide for example usage.
getEntry()
Section titled getEntry()
Added in:
astro@2.5.0
类型:
¥Types:
-
(collection: string, contentSlugOrDataId: string) => CollectionEntry<TCollectionName>
-
({ collection: string, id: string }) => CollectionEntry<TCollectionName>
-
({ collection: string, slug: string }) => CollectionEntry<TCollectionName>
getEntry()
是一个按集合名称和条目 id
(对于 type: 'data'
集合)或条目 slug
(对于 type: 'content'
集合)检索单个集合条目的函数。getEntry()
还可用于获取引用条目以访问 data
、body
或 render()
属性:
¥getEntry()
is a function that retrieves a single collection entry by collection name and either the entry id
(for type: 'data'
collections) or entry slug
(for type: 'content'
collections). getEntry()
can also be used to get referenced entries to access the data
, body
, or render()
properties:
有关 查询集合条目 的示例,请参阅 Content Collections
指南。
¥See the Content Collections
guide for examples of querying collection entries.
getEntries()
Section titled getEntries()
Added in:
astro@2.5.0
类型:
¥Types:
-
(Array<{ collection: string, id: string }>) => CollectionEntry<TCollectionName>[]
-
(Array<{ collection: string, slug: string }>) => CollectionEntry<TCollectionName>[]
getEntries()
是从同一集合中检索多个集合条目的函数。这对于 返回引用条目的数组 访问其关联的 data
、body
和 render()
属性很有用。
¥getEntries()
is a function that retrieves multiple collection entries from the same collection. This is useful for returning an array of referenced entries to access their associated data
, body
, and render()
properties.
getEntryBySlug()
Section titled getEntryBySlug()类型:(collection: string, slug: string) => Promise<CollectionEntry<TCollectionName>>
¥Type: (collection: string, slug: string) => Promise<CollectionEntry<TCollectionName>>
getEntryBySlug()
是一个通过集合名称和条目 slug
检索单个集合条目的函数。
¥getEntryBySlug()
is a function that retrieves a single collection entry by collection name and entry slug
.
请参阅 Content Collection
指南 例如用法。
¥See the Content Collection
guide for example usage.
getDataEntryById()
Section titled getDataEntryById()类型:(collection: string, id: string) => Promise<CollectionEntry<TCollectionName>>
¥Type: (collection: string, id: string) => Promise<CollectionEntry<TCollectionName>>
astro@2.5.0
getDataEntryById()
是一个通过集合名称和条目 id
检索单个集合条目的函数。
¥getDataEntryById()
is a function that retrieves a single collection entry by collection name and entry id
.
集合条目类型
Section titled 集合条目类型¥Collection Entry Type
包括 getCollection()
、getEntry()
和 getEntries()
在内的查询函数均返回 CollectionEntry
类型的条目。该类型可作为 astro:content
中的实用程序使用:
¥Query functions including getCollection()
, getEntry()
, and getEntries()
each return entries with the CollectionEntry
type. This type is available as a utility from astro:content
:
CollectionEntry<TCollectionName>
类型是具有以下值的对象。TCollectionName
是你正在查询的集合的名称(例如 CollectionEntry<'blog'>
)。
¥The CollectionEntry<TCollectionName>
type is an object with the following values. TCollectionName
is the name of the collection you’re querying (e.g. CollectionEntry<'blog'>
).
可以用来:type: 'content'
和 type: 'data'
集合示例类型:
¥Available for: type: 'content'
and type: 'data'
collections
Example Types:
-
内容合集:
'entry-1.md' | 'entry-2.md' | ...
-
数据收集:
'author-1' | 'author-2' | ...
使用相对于 src/content/[collection]
的文件路径的唯一 ID。根据集合条目文件路径枚举所有可能的字符串值。请注意,集合 定义为 type: 'content'
在其 ID 中包含文件扩展名,而定义为 type: 'data'
的集合则不包含文件扩展名。
¥A unique ID using the file path relative to src/content/[collection]
. Enumerates all possible string values based on the collection entry file paths. Note that collections defined as type: 'content'
include the file extension in their ID, while collections defined as type: 'data'
do not.
collection
Section titled collection可以用来:type: 'content'
和 type: 'data'
集合示例类型:'blog' | 'authors' | ...
¥Available for: type: 'content'
and type: 'data'
collections
Example Type: 'blog' | 'authors' | ...
src/content/
下条目所在的顶层文件夹的名称。这是用于在架构和查询函数中引用集合的名称。
¥The name of a top-level folder under src/content/
in which entries are located. This is the name used to reference the collection in your schema, and in querying functions.
可以用来:type: 'content'
和 type: 'data'
集合类型:CollectionSchema<TCollectionName>
¥Available for: type: 'content'
and type: 'data'
collections
Type: CollectionSchema<TCollectionName>
从集合架构 (参见 defineCollection()
参考) 推断出的 frontmatter 属性的对象。如果未配置架构,则默认为 any
。
¥An object of frontmatter properties inferred from your collection schema (see defineCollection()
reference). Defaults to any
if no schema is configured.
可以用来:仅限 type: 'content'
集合示例类型:'entry-1' | 'entry-2' | ...
¥Available for: type: 'content'
collections only
Example Type: 'entry-1' | 'entry-2' | ...
用于 Markdown 或 MDX 文档的 URL 就绪 slug。默认为 id
,不带文件扩展名,但可以通过在文件的 frontmatter 中设置 slug
属性 来覆盖。
¥A URL-ready slug for Markdown or MDX documents. Defaults to the id
without the file extension, but can be overridden by setting the slug
property in a file’s frontmatter.
可以用来:仅 type: 'content'
集合类型:string
¥Available for: type: 'content'
collections only
Type: string
包含 Markdown 或 MDX 文档的原始未编译正文的字符串。
¥A string containing the raw, uncompiled body of the Markdown or MDX document.
render()
Section titled render()可以用来:仅 type: 'content'
集合类型:() => Promise<RenderedEntry>
¥Available for: type: 'content'
collections only
Type: () => Promise<RenderedEntry>
编译给定 Markdown 或 MDX 文档以进行渲染的函数。这将返回以下属性:
¥A function to compile a given Markdown or MDX document for rendering. This returns the following properties:
-
<Content />
- 用于在 Astro 文件中渲染文档内容的组件。 -
headings
- 生成的标题列表,Markdown 上的 镜像 Astro 的getHeadings()
实用程序 和 MDX 导入。 -
remarkPluginFrontmatter
- 任何 已应用评论或 rehype 插件 之后修改后的 frontmatter 对象。设置为类型any
。
请参阅 Content Collection
指南 例如用法。
¥See the Content Collection
guide for example usage.
其他内容集合类型
Section titled 其他内容集合类型¥Other Content Collection Types
astro:content
模块还导出以下类型以在你的 Astro 项目中使用:
¥The astro:content
module also exports the following types for use in your Astro project:
CollectionKey
Section titled CollectionKey
Added in:
astro@3.1.0
src/content/config.*
文件中定义的所有集合名称的字符串并集。在定义接受任何集合名称的通用函数时,此类型非常有用。
¥A string union of all collection names defined in your src/content/config.*
file. This type can be useful when defining a generic function that accepts any collection name.
ContentCollectionKey
Section titled ContentCollectionKey
Added in:
astro@3.1.0
src/content/config.*
文件中定义的 type: 'content'
集合的所有名称的字符串并集。
¥A string union of all the names of type: 'content'
collections defined in your src/content/config.*
file.
DataCollectionKey
Section titled DataCollectionKey
Added in:
astro@3.1.0
src/content/config.*
文件中定义的 type: 'data'
集合的所有名称的字符串并集。
¥A string union of all the names of type: 'data'
collection defined in your src/content/config.*
file.
SchemaContext
Section titled SchemaContextdefineCollection
用于 schema
函数形状的 context
对象。在为多个集合构建可重用架构时,此类型非常有用。
¥The context
object that defineCollection
uses for the function shape of schema
. This type can be useful when building reusable schemas for multiple collections.
这包括以下属性:
¥This includes the following property:
image
- 允许你 在资源库中使用本地图片 的image()
模式助手
中间件(astro:middleware
)
Section titled 中间件(astro:middleware)¥Middleware (astro:middleware
)
Added in:
astro@2.6.0
中间件允许你拦截请求和响应,并在每次页面或端点即将渲染时动态注入行为。有关功能和使用示例,请参阅我们的中间件指南。
¥Middleware allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered. For features and usage examples, see our middleware guide.
onRequest()
Section titled onRequest()类型:(context: APIContext, next: MiddlewareNext) => Promise<Response> | Response | Promise<void> | void
¥Type: (context: APIContext, next: MiddlewareNext) => Promise<Response> | Response | Promise<void> | void
src/middleware.js
中必需的导出函数,将在渲染每个页面或 API 路由之前调用。它接收两个参数:context 和 next()。onRequest()
必须返回 Response
:直接或通过致电 next()
。
¥A required exported function from src/middleware.js
that will be called before rendering every page or API route. It receives two arguments: context and next(). onRequest()
must return a Response
: either directly, or by calling next()
.
context
Section titled context类型:APIContext
¥Type: APIContext
onRequest()
的第一个参数是上下文对象。它反映了 Astro
的许多全局属性。
¥The first argument of onRequest()
is a context object. It mirrors many of the Astro
global properties.
next()
Section titled next()类型:(rewritePayload?: string | URL | Request) => Promise<Response>
¥Type: (rewritePayload?: string | URL | Request) => Promise<Response>
onRequest()
的第二个参数是一个函数,它调用链中的所有后续中间件并返回 Response
。例如,其他中间件可以修改响应的 HTML 主体,等待 next()
的结果将允许你的中间件响应这些更改。
¥The second argument of onRequest()
is a function that calls all the subsequent middleware in the chain and returns a Response
. For example, other middleware could modify the HTML body of a response and awaiting the result of next()
would allow your middleware to respond to those changes.
自 Astro v4.13.0 起,next()
接受字符串、URL
或 Request
到 rewrite 形式的可选 URL 路径参数,而无需重新触发新的渲染阶段。
¥Since Astro v4.13.0, next()
accepts an optional URL path parameter in the form of a string, URL
, or Request
to rewrite the current request without retriggering a new rendering phase.
sequence()
Section titled sequence()类型:(...handlers: MiddlewareHandler[]) => MiddlewareHandler
¥Type: (...handlers: MiddlewareHandler[]) => MiddlewareHandler
接受中间件函数作为参数的函数,并将按照传递它们的顺序执行它们。
¥A function that accepts middleware functions as arguments, and will execute them in the order in which they are passed.
createContext()
Section titled createContext()类型:(context: CreateContext) => APIContext
¥Type: (context: CreateContext) => APIContext
astro@2.8.0
一个底层 API,用于创建要传递给 Astro 中间件 onRequest()
函数的 APIContext
。
¥A low-level API to create an APIContext
to be passed to an Astro middleware onRequest()
function.
集成/适配器可以使用此函数以编程方式执行 Astro 中间件。
¥This function can be used by integrations/adapters to programmatically execute the Astro middleware.
trySerializeLocals()
Section titled trySerializeLocals()类型:(value: unknown) => string
¥Type: (value: unknown) => string
astro@2.8.0
一个底层 API,它接受任何值并尝试返回它的序列化版本(字符串)。如果该值无法序列化,该函数将抛出运行时错误。
¥A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error.
国际化 (astro:i18n
)
Section titled 国际化 (astro:i18n)¥Internationalization (astro:i18n
)
Added in:
astro@3.5.0
此模块提供功能来帮助你使用项目配置的语言环境创建 URL。
¥This module provides functions to help you create URLs using your project’s configured locales.
使用 i18n 路由为你的项目创建路由将取决于你设置的影响页面路由的某些配置值。使用这些功能创建路由时,请务必考虑你的个人设置:
¥Creating routes for your project with the i18n router will depend on certain configuration values you have set that affect your page routes. When creating routes with these functions, be sure to take into account your individual settings for:
另请注意,这些函数为你的 defaultLocale
创建的返回 URL 将反映你的 i18n.routing
配置。
¥Also, note that the returned URLs created by these functions for your defaultLocale
will reflect your i18n.routing
configuration.
有关功能和使用示例,查看我们的 i18n 路由指南。
¥For features and usage examples, see our i18n routing guide.
getRelativeLocaleUrl()
Section titled getRelativeLocaleUrl()类型:(locale: string, path?: string, options?: GetLocaleOptions) => string
¥Type: (locale: string, path?: string, options?: GetLocaleOptions) => string
使用此函数检索区域设置的相对路径。如果区域设置不存在,Astro 会抛出错误。
¥Use this function to retrieve a relative path for a locale. If the locale doesn’t exist, Astro throws an error.
getAbsoluteLocaleUrl()
Section titled getAbsoluteLocaleUrl()类型:(locale: string, path: string, options?: GetLocaleOptions) => string
¥Type: (locale: string, path: string, options?: GetLocaleOptions) => string
当 [site
] 有值时,使用此函数检索语言环境的绝对路径。如果未配置 [site
],则该函数返回相对 URL。如果区域设置不存在,Astro 会抛出错误。
¥Use this function to retrieve an absolute path for a locale when [site
] has a value. If [site
] isn’t configured, the function returns a relative URL. If the locale doesn’t exist, Astro throws an error.
getRelativeLocaleUrlList()
Section titled getRelativeLocaleUrlList()类型:(path?: string, options?: GetLocaleOptions) => string[]
¥Type: (path?: string, options?: GetLocaleOptions) => string[]
像 getRelativeLocaleUrl
这样使用它可以返回所有语言环境的相对路径列表。
¥Use this like getRelativeLocaleUrl
to return a list of relative paths for all the locales.
getAbsoluteLocaleUrlList()
Section titled getAbsoluteLocaleUrlList()类型:(path?: string, options?: GetLocaleOptions) => string[]
¥Type: (path?: string, options?: GetLocaleOptions) => string[]
像 getAbsoluteLocaleUrl
这样使用它可以返回所有语言环境的绝对路径列表。
¥Use this like getAbsoluteLocaleUrl
to return a list of absolute paths for all the locales.
getPathByLocale()
Section titled getPathByLocale()类型:(locale: string) => string
¥Type: (locale: string) => string
配置 自定义区域设置路径 时返回与一个或多个 codes
关联的 path
的函数。
¥A function that returns the path
associated to one or more codes
when custom locale paths are configured.
getLocaleByPath()
Section titled getLocaleByPath()类型:(path: string) => string
¥Type: (path: string) => string
返回与区域设置 path
关联的 code
的函数。
¥A function that returns the code
associated to a locale path
.
redirectToDefaultLocale()
Section titled redirectToDefaultLocale()类型:(context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>
¥Type: (context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>
astro@4.6.0
返回重定向到配置的 defaultLocale
的 Response
的函数。它接受可选的有效重定向状态代码。
¥A function that returns a Response
that redirects to the defaultLocale
configured. It accepts an optional valid redirect status code.
redirectToFallback()
Section titled redirectToFallback()类型:(context: APIContext, response: Response) => Promise<Response>
¥Type: (context: APIContext, response: Response) => Promise<Response>
astro@4.6.0
允许你在自己的中间件中使用 i18n.fallback
configuration 的函数。
¥A function that allows you to use your i18n.fallback
configuration in your own middleware.
notFound()
Section titled notFound()类型:(context: APIContext, response?: Response) => Promise<Response> | undefined
¥Type: (context: APIContext, response?: Response) => Promise<Response> | undefined
astro@4.6.0
在以下情况下,在路由中间件中使用此功能返回 404:
¥Use this function in your routing middleware to return a 404 when:
-
当前路径不是根路径。例如
/
或/<base>
-
URL 不包含语言环境
传递 Response
后,此函数发出的新 Response
将包含与原始响应相同的标头。
¥When a Response
is passed, the new Response
emitted by this function will contain the same headers of the original response.
middleware()
Section titled middleware()类型:(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler
¥Type: (options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler
astro@4.6.0
允许你以编程方式创建 Astro i18n 中间件的函数。
¥A function that allows you to programmatically create the Astro i18n middleware.
当你仍想使用默认的 i18n 逻辑,但只为你的网站添加一些例外时,这很有用。
¥This is use useful when you still want to use the default i18n logic, but add only a few exceptions to your website.
requestHasLocale()
Section titled requestHasLocale()类型:(context: APIContext) => boolean
¥Type: (context: APIContext) => boolean
astro@4.6.0
检查当前 URL 是否包含配置的语言环境。在内部,此功能将使用 APIContext#url.pathname
。
¥Checks whether the current URL contains a configured locale. Internally, this function will use APIContext#url.pathname
.
查看 Transitions 客户端 API (astro:transitions/client
)
Section titled 查看 Transitions 客户端 API (astro:transitions/client)¥View Transitions client API (astro:transitions/client
)
Added in:
astro@3.2.0
此模块提供控制和与 View Transitions API 和客户端路由交互的功能。
¥This module provides functions to control and interact with the View Transitions API and client-side router.
有关功能和使用示例,请参阅我们的“查看转换”指南。
¥For features and usage examples, see our View Transitions guide.
navigate()
Section titled navigate()类型:(href: string, options?: Options) => void
¥Type: (href: string, options?: Options) => void
astro@3.2.0
使用 View Transitions API 执行到给定 href
的导航的函数。
¥A function that executes a navigation to the given href
using the View Transitions API.
此函数签名基于 来自浏览器导航 API 的 navigate
函数。尽管基于导航 API,但此功能是在 历史 API 之上实现的,以允许导航而无需重新加载页面。
¥This function signature is based on the navigate
function from the browser Navigation API. Although based on the Navigation API, this function is implemented on top of the History API to allow for navigation without reloading the page.
history
选项
Section titled history 选项¥history
option
类型:'auto' | 'push' | 'replace'
默认:'auto'
¥Type: 'auto' | 'push' | 'replace'
Default: 'auto'
astro@3.2.0
定义应如何将此导航添加到浏览器历史记录中。
¥Defines how this navigation should be added to the browser history.
-
'push'
:路由将使用history.pushState
在浏览器历史记录中创建一个新条目。 -
'replace'
:路由将使用history.replaceState
更新 URL,而不添加新的导航条目。 -
'auto'
(默认):路由将尝试history.pushState
,但如果无法转换到 URL,则当前 URL 将保持不变,浏览器历史记录不会发生任何变化。
此选项遵循浏览器导航 API 中的 history
选项,但针对 Astro 项目中可能发生的情况进行了简化。
¥This option follows the history
option from the browser Navigation API but simplified for the cases that can happen on an Astro project.
formData
选项
Section titled formData 选项¥formData
option
类型:FormData
¥Type: FormData
astro@3.5.0
POST
请求的 FormData
对象。
¥A FormData
object for POST
requests.
提供此选项后,对导航目标页面的请求将作为 POST
请求发送,其中表单数据对象作为内容。
¥When this option is provided, the requests to the navigation target page will be sent as a POST
request with the form data object as the content.
提交启用视图转换的 HTML 表单将使用此方法,而不是使用页面重新加载的默认导航。调用此方法允许以编程方式触发相同的行为。
¥Submitting an HTML form with view transitions enabled will use this method instead of the default navigation with page reload. Calling this method allows triggering the same behavior programmatically.
info
选项
Section titled info 选项¥info
option
类型:any
¥Type: any
astro@3.6.0
此导航引起的 astro:before-preparation
和 astro:before-swap
事件中将包含任意数据。
¥Arbitrary data to be included in the astro:before-preparation
and astro:before-swap
events caused by this navigation.
此选项模仿浏览器导航 API 中的 info
选项。
¥This option mimics the info
option from the browser Navigation API.
state
选项
Section titled state 选项¥state
option
类型:any
¥Type: any
astro@3.6.0
与此导航创建的 NavitationHistoryEntry
对象关联的任意数据。然后可以使用 History API 中的 history.getState
function 检索此数据。
¥Arbitrary data to be associated with the NavitationHistoryEntry
object created by this navigation. This data can then be retrieved using the history.getState
function from the History API.
此选项模仿浏览器导航 API 中的 state
选项。
¥This option mimics the state
option from the browser Navigation API.
sourceElement
选项
Section titled sourceElement 选项¥sourceElement
option
类型:Element
¥Type: Element
astro@3.6.0
触发此导航的元素(如果有)。此元素将在以下事件中可用:
¥The element that triggered this navigation, if any. This element will be available in the following events:
-
astro:before-preparation
-
astro:before-swap
supportsViewTransitions
Section titled supportsViewTransitions类型:boolean
¥Type: boolean
astro@3.2.0
当前浏览器是否支持并启用视图转换。
¥Whether or not view transitions are supported and enabled in the current browser.
transitionEnabledOnThisPage
Section titled transitionEnabledOnThisPage类型:boolean
¥Type: boolean
astro@3.2.0
当前页面是否为客户端导航启用了视图转换。这可用于制作在具有视图转换的页面上使用时行为不同的组件。
¥Whether or not the current page has view transitions enabled for client-side navigation. This can be used to make components that behave differently when they are used on pages with view transitions.
getFallback
Section titled getFallback类型:() => 'none' | 'animate' | 'swap'
¥Type: () => 'none' | 'animate' | 'swap'
astro@3.6.0
返回不支持视图转换的浏览器中使用的后备策略。
¥Returns the fallback strategy to use in browsers that do not support view transitions.
有关如何选择和配置后备行为,请参阅 回退控制 指南。
¥See the guide on Fallback control for how to choose and configure the fallback behavior.
astro:before-preparation
事件
Section titled astro:before-preparation 事件¥astro:before-preparation
event
使用视图转换在导航开始时分派的事件。此事件发生在发出任何请求和更改任何浏览器状态之前。
¥An event dispatched at the beginning of a navigation using View Transitions. This event happens before any request is made and any browser state is changed.
此事件具有以下属性:
¥This event has the attributes:
阅读有关如何在 查看转换指南 上使用此事件的更多信息。
¥Read more about how to use this event on the View Transitions guide.
astro:after-preparation
事件
Section titled astro:after-preparation 事件¥astro:after-preparation
event
使用视图转换的导航中的下一页加载后分派的事件。
¥An event dispatched after the next page in a navigation using View Transitions is loaded.
此事件没有属性。
¥This event has no attributes.
阅读有关如何在 查看转换指南 上使用此事件的更多信息。
¥Read more about how to use this event on the View Transitions guide.
astro:before-swap
事件
Section titled astro:before-swap 事件¥astro:before-swap
event
在解析、准备下一页并将其链接到文档以准备转换但在文档之间交换任何内容之前分派的事件。
¥An event dispatched after the next page is parsed, prepared, and linked into a document in preparation for the transition but before any content is swapped between the documents.
此事件无法取消。调用 preventDefault()
是无操作。
¥This event can’t be canceled. Calling preventDefault()
is a no-op.
此事件具有以下属性:
¥This event has the attributes:
阅读有关如何在 查看转换指南 上使用此事件的更多信息。
¥Read more about how to use this event on the View Transitions guide.
astro:after-swap
事件
Section titled astro:after-swap 事件¥astro:after-swap
event
页面内容交换后但在视图转换结束之前分派的事件。
¥An event dispatched after the contents of the page have been swapped but before the view transition ends.
触发此事件时,历史记录条目和滚动位置已更新。
¥The history entry and scroll position have already been updated when this event is triggered.
astro:page-load
事件
Section titled astro:page-load 事件¥astro:page-load
event
页面完成加载后分派的事件,无论是使用视图转换的导航还是浏览器原生的导航。
¥An event dispatched after a page completes loading, whether from a navigation using view transitions or native to the browser.
在页面上启用视图转换时,应将通常在 DOMContentLoaded
上执行的代码更改为在此事件上执行。
¥When view transitions is enabled on the page, code that would normally execute on DOMContentLoaded
should be changed to execute on this event.
查看 Transitions 事件属性
Section titled 查看 Transitions 事件属性¥View Transitions events attributes
Added in:
astro@3.6.0
类型:URL
¥Type: URL
导航期间定义的任意数据。
¥Arbitrary data defined during navigation.
这是在 navigate()
功能 的 info
选项 上传递的字面量值。
¥This is the literal value passed on the info
option of the navigate()
function.
sourceElement
Section titled sourceElement类型:Element | undefined
¥Type: Element | undefined
触发导航的元素。例如,这可以是被点击的 <a>
元素。
¥The element that triggered the navigation. This can be, for example, an <a>
element that was clicked.
使用 navigate()
功能 时,这将是调用中指定的元素。
¥When using the navigate()
function, this will be the element specified in the call.
newDocument
Section titled newDocument类型:Document
¥Type: Document
导航中下一页的文档。此文档的内容将替换当前文档的内容。
¥The document for the next page in the navigation. The contents of this document will be swapped in place of the contents of the current document.
navigationType
Section titled navigationType类型:'push' | 'replace' | 'traverse'
¥Type: 'push' | 'replace' | 'traverse'
正在发生哪种历史导航。
¥Which kind of history navigation is happening.
-
push
:正在为新页面创建新的NavigationHistoryEntry
。 -
replace
:当前NavigationHistoryEntry
将被新页面的条目替换。 -
traverse
:未创建NavigationHistoryEntry
。历史记录中的位置正在发生变化。遍历的方向在direction
属性 上给出
direction
Section titled direction类型:Direction
¥Type: Direction
转换的方向。
¥The direction of the transition.
-
forward
:导航到历史记录中的下一页或新页面。 -
back
:导航到历史记录中的上一页。 -
其他监听器可能设置的任何其他内容。
类型:URL
¥Type: URL
启动导航的页面的 URL。
¥The URL of the page initiating the navigation.
类型:URL
¥Type: URL
正在导航到的页面的 URL。此属性可以修改,生命周期结束时的值将在下一页的 NavigationHistoryEntry
中使用。
¥The URL of the page being navigated to. This property can be modified, the value at the end of the lifecycle will be used in the NavigationHistoryEntry
for the next page.
formData
Section titled formData类型:FormData | undefined
¥Type: FormData | undefined
POST
请求的 FormData
对象。
¥A FormData
object for POST
requests.
设置此属性后,将向 to
URL 发送 POST
请求,其中给定的表单数据对象作为内容,而不是正常的 GET
请求。
¥When this attribute is set, a POST
request will be sent to the to
URL with the given form data object as the content instead of the normal GET
request.
提交启用了视图转换的 HTML 表单时,此字段会自动设置为表单中的数据。使用 navigate()
功能 时,此值与选项中给出的值相同。
¥When submitting an HTML form with view transitions enabled, this field is automatically set to the data in the form. When using the navigate()
function, this value is the same as given in the options.
loader
Section titled loader类型:() => Promise<void>
¥Type: () => Promise<void>
导航中的以下阶段的实现(加载下一页)。可以覆盖此实现以添加额外行为。
¥Implementation of the following phase in the navigation (loading the next page). This implementation can be overridden to add extra behavior.
viewTransition
Section titled viewTransition¥Type: ViewTransition
此导航中使用的视图转换对象。在不支持 视图转换 API 的浏览器上,这是一个为方便起见实现相同 API 的对象,但没有 DOM 集成。
¥The view transition object used in this navigation. On browsers that do not support the View Transitions API, this is an object implementing the same API for convenience but without the DOM integration.
类型:() => void
¥Type: () => void
文档交换逻辑的实现。
¥Implementation of the document swap logic.
阅读有关如何在 View Transitions 指南中使用 构建你自己的自定义交换函数 的更多信息。
¥Read more on how to build your own custom swap function on the View Transitions guide.
默认情况下,此实现将按顺序调用以下函数:
¥By default, this implementation will call the following functions in order:
deselectScripts()
Section titled deselectScripts()类型:(newDocument: Document) => void
¥Type: (newDocument: Document) => void
在新文档中标记不应执行的脚本。这些脚本已在当前文档中,并且未使用 data-astro-rerun
标记为重新执行。
¥Marks scripts in the new document that should not be executed. Those scripts are already in the current document and are not flagged for re-execution using data-astro-rerun
.
swapRootAttributes()
Section titled swapRootAttributes()类型:(newDocument: Document) => void
¥Type: (newDocument: Document) => void
在文档根之间交换属性,如 lang
属性。这还包括 Astro 注入的内部属性,如 data-astro-transition
,这使得转换方向可用于 Astro 生成的 CSS 规则。
¥Swaps the attributes between the document roots, like the lang
attribute. This also includes Astro-injected internal attributes like data-astro-transition
, which makes the transition direction available to Astro-generated CSS rules.
制作自定义交换函数时,调用此函数很重要,以免破坏视图转换的动画。
¥When making a custom swap function, it is important to call this function so as not to break the view transition’s animations.
swapHeadElements()
Section titled swapHeadElements()类型:(newDocument: Document) => void
¥Type: (newDocument: Document) => void
从当前文档的 <head>
中删除未保留到新文档的每个元素。然后将新文档的 <head>
中的所有新元素附加到当前文档的 <head>
。
¥Removes every element from the current document’s <head>
that is not persisted to the new document. Then appends all new elements from the new document’s <head>
to the current document’s <head>
.
saveFocus()
Section titled saveFocus()类型:() => () => void
¥Type: () => () => void
将焦点元素存储在当前页面上并返回一个函数,如果焦点元素被持久化,则在调用该函数时将焦点返回给它。
¥Stores the element in focus on the current page and returns a function that when called, if the focused element was persisted, returns the focus to it.
swapBodyElements()
Section titled swapBodyElements()类型:(newBody: Element, oldBody: Element) => void
¥Type: (newBody: Element, oldBody: Element) => void
用新主体替换旧主体。然后,遍历旧主体中应保留的每个元素,并在新主体中具有匹配的元素,然后将旧元素交换回原位。
¥Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place.
操作 (astro:actions
)
Section titled 操作 (astro:actions)¥Actions (astro:actions
)
Added in:
astro@4.15.0
操作可帮助你构建可从客户端代码和 HTML 表单调用的类型安全后端。定义和调用操作的所有实用程序都由 astro:actions
模块公开。有关示例和使用说明,请参阅 请参阅“操作”指南。
¥Actions help you build a type-safe backend you can call from client code and HTML forms. All utilities to define and call actions are exposed by the astro:actions
module. For examples and usage instructions, see the Actions guide.
defineAction()
Section titled defineAction()
Added in:
astro@4.15.0
defineAction()
实用程序用于从 src/actions/index.ts
文件定义新操作。这接受包含要运行的服务器逻辑的 handler()
函数,以及可选的 input
属性以在运行时验证输入参数。
¥The defineAction()
utility is used to define new actions from the src/actions/index.ts
file. This accepts a handler()
function containing the server logic to run, and an optional input
property to validate input parameters at runtime.
handler()
属性
Section titled handler() 属性¥handler()
property
类型:(input, context) => any
¥Type: (input, context) => any
defineAction()
需要一个 handler()
函数,其中包含在调用操作时运行的服务器逻辑。从处理程序返回的数据会自动序列化并发送给调用者。
¥defineAction()
requires a handler()
function containing the server logic to run when the action is called. Data returned from the handler is automatically serialized and sent to the caller.
handler()
以用户输入作为其第一个参数进行调用。如果设置了 input
验证器,则在将用户输入传递给处理程序之前,将对其进行验证。第二个参数是一个 context
对象,包含 Astro 的大部分 标准端点上下文,但不包括 getActionResult()
、callAction()
和 redirect()
。
¥The handler()
is called with user input as its first argument. If an input
validator is set, the user input will be validated before being passed to the handler. The second argument is a context
object containing most of Astro’s standard endpoint context, excluding getActionResult()
, callAction()
, and redirect()
.
使用 贬值库 解析返回值。这支持 JSON 值和 Date()
、Map()
、Set()
和 URL()
的实例。
¥Return values are parsed using the devalue library. This supports JSON values and instances of Date()
, Map()
, Set()
, and URL()
.
input
验证器
Section titled input 验证器¥input
validator
类型:ZodType | undefined
¥Type: ZodType | undefined
可选的 input
属性接受 Zod 验证器以在运行时验证处理程序输入。如果操作验证失败,则返回 BAD_REQUEST
错误,并且不会调用 handler
。
¥The optional input
property accepts a Zod validator to validate handler inputs at runtime. If the action fails to validate, a BAD_REQUEST
error is returned and the handler
is not called.
如果省略 input
,handler
将接收 JSON 请求的 unknown
类型输入和表单请求的 FormData
类型输入。
¥If input
is omitted, the handler
will receive an input of type unknown
for JSON requests and type FormData
for form requests.
与 accept: 'form'
一起使用
Section titled 与 accept: 'form' 一起使用¥Use with accept: 'form'
如果你的操作接受表单输入,请使用 z.object()
验证器自动将表单数据解析为类型化对象。表单数据字段支持以下验证器:
¥If your action accepts form inputs, use the z.object()
validator to automatically parse form data to a typed object. The following validators are supported for form data fields:
-
可以使用
z.number()
验证类型为number
的输入 -
可以使用
z.boolean()
验证类型为checkbox
的输入 -
可以使用
z.instanceof(File)
验证类型为file
的输入 -
可以使用
z.array(/* validator */)
验证相同name
的多个输入 -
所有其他输入都可以使用
z.string()
进行验证
z.object()
验证器还支持扩展函数,包括 .refine()
、.transform()
和 .pipe()
。
¥Extension functions including .refine()
, .transform()
, and .pipe()
are also supported on the z.object()
validator.
要应用不同验证器的联合,请使用 z.discriminatedUnion()
封装器根据特定表单字段缩小类型。此示例接受向 “create” 或 “update” 用户提交的表单,使用名为 type
的表单字段来确定要针对哪个对象进行验证:
¥To apply a union of different validators, use the z.discriminatedUnion()
wrapper to narrow the type based on a specific form field. This example accepts a form submission to either “create” or “update” a user, using the form field with the name type
to determine which object to validate against:
isInputError()
Section titled isInputError()类型:(error?: unknown | ActionError) => boolean
¥Type: (error?: unknown | ActionError) => boolean
astro@4.15.0
isInputError()
实用程序用于检查 ActionError
是否为输入验证错误。当 input
验证器是 z.object()
时,输入错误包含一个 fields
对象,其中的错误消息按名称分组。
¥The isInputError()
utility is used to check whether an ActionError
is an input validation error. When the input
validator is a z.object()
, input errors include a fields
object with error messages grouped by name.
isInputError()
.
ActionError
Section titled ActionError
Added in:
astro@4.15.0
ActionError()
构造函数用于创建由操作 handler
抛出的错误。这接受一个描述所发生错误的 code
属性(例如:"UNAUTHORIZED"
),以及一个包含更多详细信息的可选 message
属性。
¥The ActionError()
constructor is used to create errors thrown by an action handler
. This accepts a code
property describing the error that occurred (example: "UNAUTHORIZED"
), and an optional message
property with further details.
Added in:
astro@4.15.0
code
属性接受所有 HTTP 状态代码的人类可读版本。支持以下代码:
¥The code
property accepts human-readable versions of all HTTP status codes. The following codes are supported:
-
BAD_REQUEST
(400):客户端发送了无效输入。当操作input
验证器验证失败时,会抛出此错误。 -
UNAUTHORIZED
(401):客户端缺少有效的身份验证凭据。 -
FORBIDDEN
(403):客户端无权访问资源。 -
NOT_FOUND
(404):服务器找不到请求的资源。 -
METHOD_NOT_SUPPORTED
(405):服务器不支持请求的方法。 -
TIMEOUT
(408):服务器在处理请求时超时。 -
CONFLICT
(409):由于冲突,服务器无法更新资源。 -
PRECONDITION_FAILED
(412):服务器不满足请求的先决条件。 -
PAYLOAD_TOO_LARGE
(413):服务器无法处理请求,因为有效负载太大。 -
UNSUPPORTED_MEDIA_TYPE
(415):服务器不支持请求的媒体类型。注意:操作已经检查了Content-Type
标头 的 JSON 和表单请求,因此你可能不需要手动引发此代码。 -
UNPROCESSABLE_CONTENT
(422):由于语义错误,服务器无法处理请求。 -
TOO_MANY_REQUESTS
(429):服务器已超过指定的速率限制。 -
CLIENT_CLOSED_REQUEST
(499):客户端在服务器响应之前关闭了请求。 -
INTERNAL_SERVER_ERROR
(500):服务器意外失败。 -
NOT_IMPLEMENTED
(501):服务器不支持请求的功能。 -
BAD_GATEWAY
(502):服务器从上游服务器收到无效响应。 -
SERVICE_UNAVAILABLE
(503):服务器暂时不可用。 -
GATEWAY_TIMEOUT
(504):服务器从上游服务器收到超时。
message
Section titled message
Added in:
astro@4.15.0
message
属性接受一个字符串。(例如 “用户必须登录。“)
¥The message
property accepts a string. (e.g. “User must be logged in.“)