Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

传递到 handleevent 对象是同一个对象 - 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:

  • cookiescookies API

  • fetch — 标准 Fetch API,具有附加功能

    ¥fetch — the standard Fetch API, with additional powers

  • getClientAddress() — 获取客户端 IP 地址的函数

    ¥getClientAddress() — a function to get the client’s IP address

  • isDataRequest — 如果浏览器在客户端导航期间请求页面数据,则为 true;如果直接请求页面/路由,则为 false

    ¥isDataRequesttrue if the browser is requesting data for a page during client-side navigation, false if a page/route is being requested directly

  • locals — 放置任意数据的地方

    ¥locals — a place to put arbitrary data

  • params — 路由参数

    ¥params — the route parameters

  • request请求 对象

    ¥request — the Request object

  • route — 具有 id 属性的对象,表示匹配的路由

    ¥route — an object with an id property representing the route that was matched

  • setHeaders(...) — 响应上的 设置 HTTP 标头 函数

    ¥setHeaders(...) — a function for setting HTTP headers on the response

  • url — 表示当前请求的 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:

src/hooks.server
export async function handle({ event, resolve }) {
	event.locals.answer = 42;
	return await resolve(event);
}
src/routes/+page.server
export function load(event) {
	return {
		message: `the answer is ${event.locals.answer}`
	};
}
上一页 下一页
1
2
3
4
5
<script>
	let { data } = $props();
</script>
 
<h1>{data.message}</h1>