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

event 对象有一个 fetch 方法,其行为类似于标准 Fetch API,但具有超能力:

¥The event object has a fetch method that behaves like the standard Fetch API, but with superpowers:

  • 它可用于在服务器上发出凭证请求,因为它从传入请求中继承了 cookieauthorization 标头

    ¥it can be used to make credentialed requests on the server, as it inherits the cookie and authorization headers from the incoming request

  • 它可以在服务器上发出相对请求(通常,fetch 在服务器上下文中使用时需要具有来源的 URL)

    ¥it can make relative requests on the server (ordinarily, fetch requires a URL with an origin when used in a server context)

  • 内部请求(例如,对于 +server.js 路由)在服务器上运行时直接转到处理程序函数,而无需 HTTP 调用的开销

    ¥internal requests (e.g. for +server.js routes) go directly to the handler function when running on the server, without the overhead of an HTTP call

它的行为可以通过 handleFetch 钩子进行修改,默认情况下如下所示:

¥Its behaviour can be modified with the handleFetch hook, which by default looks like this:

src/hooks.server
export async function handleFetch({ event, request, fetch }) {
	return await fetch(request);
}

例如,我们可以用来自 src/routes/b/+server.js 的响应来响应对 src/routes/a/+server.js 的请求:

¥For example, we could respond to requests for src/routes/a/+server.js with responses from src/routes/b/+server.js instead:

src/hooks.server
export async function handleFetch({ event, request, fetch }) {
	const url = new URL(request.url);
	if (url.pathname === '/a') {
		return await fetch('/b');
	}

	return await fetch(request);
}

稍后,当我们介绍 通用 load 函数 时,我们将看到 event.fetch 也可以从浏览器中调用。在这种情况下,如果你从浏览器请求公共 URL(如 https://api.yourapp.com),则 handleFetch 很有用,在服务器上运行时,该请求应重定向到内部 URL(绕过 API 服务器和公共互联网之间的任何代理和负载平衡器)。

¥Later, when we cover universal load functions, we’ll see that event.fetch can also be called from the browser. In that scenario, handleFetch is useful if you have requests to a public URL like https://api.yourapp.com from the browser, that should be redirected to an internal URL (bypassing whatever proxies and load balancers sit between the API server and the public internet) when running on the server.

上一页 下一页
1
2
3
4
5
<script>
	let { data } = $props();
</script>
 
<h1>{data.message}</h1>