传递到 handle
的 event
对象是同一个对象 - RequestEvent
的一个实例 - 传递到 +server.js
文件中的 API 路由、+page.server.js
文件中的 表单操作 以及 +page.server.js
和 +layout.server.js
中的 load
函数。
¥The event
object passed into handle
is the same object — an instance of a RequestEvent
— that is passed into API routes in +server.js
files, form actions in +page.server.js
files, and load
functions in +page.server.js
and +layout.server.js
.
它包含许多有用的属性和方法,其中一些我们已经遇到过:
¥It contains a number of useful properties and methods, some of which we’ve already encountered:
cookies
— cookies APIfetch
— 标准 Fetch API,具有附加功能¥
fetch
— the standard Fetch API, with additional powersgetClientAddress()
— 获取客户端 IP 地址的函数¥
getClientAddress()
— a function to get the client’s IP addressisDataRequest
— 如果浏览器在客户端导航期间请求页面数据,则为true
;如果直接请求页面/路由,则为false
¥
isDataRequest
—true
if the browser is requesting data for a page during client-side navigation,false
if a page/route is being requested directlylocals
— 放置任意数据的地方¥
locals
— a place to put arbitrary dataparams
— 路由参数¥
params
— the route parametersrequest
— 请求 对象¥
request
— the Request objectroute
— 具有id
属性的对象,表示匹配的路由¥
route
— an object with anid
property representing the route that was matchedsetHeaders(...)
— 响应上的 设置 HTTP 标头 函数¥
setHeaders(...)
— a function for setting HTTP headers on the responseurl
— 表示当前请求的 URL 对象¥
url
— a URL object representing the current request
一个有用的模式是在 handle
中向 event.locals
添加一些数据,以便可以在后续的 load
函数中读取它:
¥A useful pattern is to add some data to event.locals
in handle
so that it can be read in subsequent load
functions:
export async function handle({ event, resolve }) {
event.locals.answer = 42;
return await resolve(event);
}
export function load(event) {
return {
message: `the answer is ${event.locals.answer}`
};
}
<script>
let { data } = $props();
</script>
<h1>{data.message}</h1>