Skip to content

中间件 API 参考

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.

astro:middleware 导入

标题部分 从 astro:middleware 导入

¥Imports from astro:middleware

import {
sequence,
createContext,
trySerializeLocals,
defineMiddleware,
} from 'astro:middleware';

你可以导入并使用实用函数 defineMiddleware() 来利用类型安全:

¥You can import and use the utility function defineMiddleware() to take advantage of type safety:

src/middleware.ts
import { defineMiddleware } from "astro:middleware";
// `context` and `next` are automatically typed
export const onRequest = defineMiddleware((context, next) => {
});

类型:(...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.

src/middleware.js
import { sequence } from "astro:middleware";
async function validation(_, next) {...}
async function auth(_, next) {...}
async function greeting(_, next) {...}
export const onRequest = sequence(validation, auth, greeting);

类型:(context: CreateContext) => APIContext

¥Type: (context: CreateContext) => APIContext

Added in: astro@2.8.0

一个底层 API,用于创建要传递给 Astro 中间件 onRequest() 函数的 APIContext

¥A low-level API to create an APIContextto be passed to an Astro middleware onRequest() function.

集成/适配器可以使用此函数以编程方式执行 Astro 中间件。

¥This function can be used by integrations/adapters to programmatically execute the Astro middleware.

类型:(value: unknown) => string

¥Type: (value: unknown) => string

Added in: 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.

¥Middleware exports

src/middleware.js 中定义项目的中间件时,导出以下用户定义函数:

¥When defining your project’s middleware in src/middleware.js, export the following user-defined functions:

类型:(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 路由之前调用。它接收两个参数:contextnext()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().

src/middleware.js
export function onRequest (context, next) {
// intercept response data from a request
// optionally, transform the response
// return a Response directly, or the result of calling `next()`
return next();
};

你的 onRequest() 函数将使用以下参数调用:

¥Your onRequest() function will be called with the following arguments:

类型:APIContext

¥Type: APIContext

onRequest() 的第一个参数是上下文对象。它反映了 Astro 的许多全局属性。

¥The first argument of onRequest() is a context object. It mirrors many of the Astro global properties.

See Endpoint contexts for more information about the context object.

类型:(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() 接受字符串、URLRequestrewrite 形式的可选 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.

Astro 中文网 - 粤ICP备13048890号