Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

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

  • it can be used to make credentialed requests on the server, as it inherits the cookie and authorization headers from the incoming request
  • it can make relative requests on the server (ordinarily, fetch requires a URL with an origin when used in a server context)
  • 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

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);
}

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);
}

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.

Edit this page on GitHub

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