Web 标准
在整个文档中,你将看到对 SvelteKit 所基于的标准 Web API 的引用。我们不是重新发明轮子,而是使用平台,这意味着你现有的 Web 开发技能适用于 SvelteKit。相反,花时间学习 SvelteKit 会帮助你在其他地方成为更好的 Web 开发者。
¥Throughout this documentation, you’ll see references to the standard Web APIs that SvelteKit builds on top of. Rather than reinventing the wheel, we use the platform, which means your existing web development skills are applicable to SvelteKit. Conversely, time spent learning SvelteKit will help you be a better web developer elsewhere.
这些 API 在所有现代浏览器和许多非浏览器环境中都可用,例如 Cloudflare Workers、Deno 和 Vercel Functions。在开发过程中,以及在基于 Node 的环境(包括 AWS Lambda)的 adapters 中,它们会在必要时通过 polyfill 提供(目前是这样 — Node 正在迅速增加对更多 Web 标准的支持)。
¥These APIs are available in all modern browsers and in many non-browser environments like Cloudflare Workers, Deno, and Vercel Functions. During development, and in adapters for Node-based environments (including AWS Lambda), they’re made available via polyfills where necessary (for now, that is — Node is rapidly adding support for more web standards).
特别是,你将熟悉以下内容:
¥In particular, you’ll get comfortable with the following:
获取 API(Fetch APIs)
¥Fetch APIs
SvelteKit 使用 fetch 从网络获取数据。它在 hooks 和 服务器路由 以及浏览器中都可用。
¥SvelteKit uses fetch for getting data from the network. It’s available in hooks and server routes as well as in the browser.
load函数、server hooks 和 API routes 中提供了特殊版本的fetch,用于在服务器端渲染期间直接调用端点,无需进行 HTTP 调用,同时保留凭据。(要在load之外的服务器端代码中进行凭据提取,必须显式传递cookie和/或authorization标头。)它还允许你发出相对请求,而服务器端fetch通常需要完全限定的 URL。
除了 fetch 本身,Fetch API 还包括以下接口:
¥Besides fetch itself, the Fetch API includes the following interfaces:
请求(Request)
¥Request
Request 的实例可在 hooks 和 服务器路由 中作为 event.request 访问。它包含有用的方法,如 request.json() 和 request.formData(),用于获取发布到端点的数据。
¥An instance of Request is accessible in hooks and server routes as event.request. It contains useful methods like request.json() and request.formData() for getting data that was posted to an endpoint.
响应(Response)
¥Response
Response 的实例由 await fetch(...) 和 +server.js 文件中的处理程序返回。从根本上说,SvelteKit 应用是将 Request 转换为 Response 的机器。
¥An instance of Response is returned from await fetch(...) and handlers in +server.js files. Fundamentally, a SvelteKit app is a machine for turning a Request into a Response.
标题(Headers)
¥Headers
Headers 接口允许你读取传入的 request.headers 并设置传出的 response.headers。例如,你可以按如下所示获取 request.headers,并使用 json 便利功能 发送修改后的 response.headers:
¥The Headers interface allows you to read incoming request.headers and set outgoing response.headers. For example, you can get the request.headers as shown below, and use the json convenience function to send modified response.headers:
import { function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json } from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */
export function function GET({ request }: {
request: any;
}): Response
GET({ request: anyrequest }) {
// log all headers
var console: ConsoleThe console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
- A global
console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format() for more information.
log(...request: anyrequest.headers);
// create a JSON Response using a header we received
return function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json({
// retrieve a specific header
userAgent: anyuserAgent: request: anyrequest.headers.get('user-agent')
}, {
// set a header on the response
ResponseInit.headers?: HeadersInit | undefinedheaders: { 'x-custom-header': 'potato' }
});
}import { function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json } from '@sveltejs/kit';
import type { type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler } from './$types';
export const const GET: RequestHandlerGET: type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler = ({ request: RequestThe original request object.
request }) => {
// log all headers
var console: ConsoleThe console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
- A global
console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format() for more information.
log(...request: RequestThe original request object.
request.Request.headers: HeadersReturns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.
headers);
// create a JSON Response using a header we received
return function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json({
// retrieve a specific header
userAgent: string | nulluserAgent: request: RequestThe original request object.
request.Request.headers: HeadersReturns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.
headers.Headers.get(name: string): string | nullget('user-agent')
}, {
// set a header on the response
ResponseInit.headers?: HeadersInit | undefinedheaders: { 'x-custom-header': 'potato' }
});
};FormData
处理 HTML 原生表单提交时,你将使用 FormData 对象。
¥When dealing with HTML native form submissions you’ll be working with FormData objects.
import { function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json } from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */
export async function function POST(event: any): Promise<Response>POST(event: anyevent) {
const const body: anybody = await event: anyevent.request.formData();
// log all fields
var console: ConsoleThe console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
- A global
console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format() for more information.
log([...const body: anybody]);
return function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json({
// get a specific field's value
name: anyname: const body: anybody.get('name') ?? 'world'
});
}import { function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json } from '@sveltejs/kit';
import type { type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler } from './$types';
export const const POST: RequestHandlerPOST: type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler = async (event: Kit.RequestEvent<Record<string, any>, string | null>event) => {
const const body: FormDatabody = await event: Kit.RequestEvent<Record<string, any>, string | null>event.RequestEvent<Record<string, any>, string | null>.request: RequestThe original request object.
request.Body.formData(): Promise<FormData>formData();
// log all fields
var console: ConsoleThe console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
- A global
console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format() for more information.
log([...const body: FormDatabody]);
return function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json({
// get a specific field's value
name: FormDataEntryValuename: const body: FormDatabody.FormData.get(name: string): FormDataEntryValue | nullget('name') ?? 'world'
});
};流 API(Stream APIs)
¥Stream APIs
大多数时候,你的端点将返回完整的数据,如上面的 userAgent 示例所示。有时,你可能需要返回一个太大而无法一次性放入内存的响应,或者需要分块传递,为此,平台提供了 streams — ReadableStream、WritableStream 和 TransformStream。
¥Most of the time, your endpoints will return complete data, as in the userAgent example above. Sometimes, you may need to return a response that’s too large to fit in memory in one go, or is delivered in chunks, and for this the platform provides streams — ReadableStream, WritableStream and TransformStream.
URL API(URL APIs)
URL 由 URL 接口表示,其中包括有用的属性,如 origin 和 pathname(以及浏览器中的 hash)。此接口出现在各个地方 - hooks 和 服务器路由 中的 event.url、pages 中的 page.url、beforeNavigate 和 afterNavigate 中的 from 和 to 等等。
¥URLs are represented by the URL interface, which includes useful properties like origin and pathname (and, in the browser, hash). This interface shows up in various places — event.url in hooks and server routes, page.url in pages, from and to in beforeNavigate and afterNavigate and so on.
URLSearchParams
无论何时遇到 URL,都可以通过 url.searchParams(URLSearchParams 的一个实例)访问查询参数:
¥Wherever you encounter a URL, you can access query parameters via url.searchParams, which is an instance of URLSearchParams:
const const foo: string | nullfoo = const url: URLurl.URL.searchParams: URLSearchParamssearchParams.URLSearchParams.get(name: string): string | nullReturns the first value associated to the given search parameter.
get('foo');Web 加密(Web Crypto)
¥Web Crypto
Web 加密 API 通过 crypto 全局提供。它在内部用于 内容安全策略 标头,但你也可以将其用于生成 UUID 之类的操作:
¥The Web Crypto API is made available via the crypto global. It’s used internally for Content Security Policy headers, but you can also use it for things like generating UUIDs:
const const uuid: `${string}-${string}-${string}-${string}-${string}`uuid = var crypto: Cryptocrypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`Available only in secure contexts.
randomUUID();