Data Overview
每个路由都能够添加 HTTP 请求和响应处理程序,允许开发人员 retrieve 和 modify 数据。 endpoints 也可以使用 请求和响应处理程序,它只响应数据而不是页面的 HTML。
此功能使您能够 在渲染组件和使用自定义内容响应之前 处理任何请求事件,对请求pipeline使用side effects。 它适用于pages、layouts和endpoint路由,但不适用于常规组件。
请求和响应处理程序
在pages、layouts和endpoints上,我们可以通过实现onGet、onPost、onPut等请求处理函数来访问请求数据。
这些函数是按照HTTP 方法 用于此路由。
此外,onRequest 函数可用于处理任何请求方法,而不是特定的方法。
例如,如果同时提供了onGet和onRequest,对于GET请求,onGet将被调用。
但是,在这种情况下,如果 POST 请求方法进来,则 onRequest 处理程序将被调用,因为没有提供 onPost。
The onRequest is available as a catch-all to any request methods that do not have a specific method.
import type { RequestHandler } from '@builder.io/qwik-city';
export const onGet: RequestHandler<ProductData> = async ({ params }) => {
// put your DB access here (hard coding data for simplicity)
return {
skuId: params.skuId,
price: 123.45,
description: `Description for ${params.skuId}`,
};
};
Request Event
请求处理函数接收一个 RequestEvent 参数,该参数具有以下属性:
| 字段 | 描述 |
|---|---|
request | The request object |
response | The response object, which can be used to set response headers and status |
url | URL which includes pathname, hostname, etc. |
next | Next middleware function |
abort | Request abort function |
params | Custom user params found within the URL |
platform | Platform data object (useful for Cloudflare, Netlify, etc) |