event
对象有一个 fetch
方法,其行为类似于标准 Fetch API,但具有超能力:
¥The event
object has a fetch
method that behaves like the standard Fetch API, but with superpowers:
它可用于在服务器上发出凭证请求,因为它从传入请求中继承了
cookie
和authorization
标头¥it can be used to make credentialed requests on the server, as it inherits the
cookie
andauthorization
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:
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:
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.
<script>
let { data } = $props();
</script>
<h1>{data.message}</h1>