从 SvelteKit 查询 D1

跳转到内容

文档索引
在以下地址获取完整文档索引:/d1/llms.txt
在进一步探索之前,使用此文件发现所有可用页面。

从 SvelteKit 查询 D1

从 SvelteKit 应用查询 D1 数据库。

最后更新:2026年4月21日|复制为 Markdown|查看 Markdown 原文|Agent setup

SvelteKit ↗︎ 是一个全栈框架,它将 Svelte 前端框架与 Vite 结合,以实现服务端能力和渲染。你可以通过配置一个服务端端点 ↗︎并绑定到你的 D1 数据库,从而从 SvelteKit 查询 D1。

要在 Cloudflare Pages 上搭建一个能够查询 D1 的新 SvelteKit 站点:

  1. 参阅 SvelteKit 指南 和 Svelte 的 Cloudflare 适配器 ↗︎。
  2. 在你的 SvelteKit 项目中安装 Cloudflare 适配器:npm i -D @sveltejs/adapter-cloudflare。
  3. 将一个 D1 数据库绑定到你的 Pages Function。
  4. 在本地开发时,向 wrangler dev 传入 --d1 BINDING_NAME=DATABASE_ID 标志。BINDING_NAME 应与你在代码中调用的名称一致,DATABASE_ID 应与你的 Wrangler 配置文件中定义的 database_id 一致:例如 --d1 DB=xxxx-xxxx-xxxx-xxxx-xxxx。

以下示例向你展示如何创建一个配置为查询 D1 的服务端端点。

  • 绑定可通过传递给每个端点的 platform 参数访问,即 platform.env.BINDING_NAME。
  • 借助 SvelteKit 的基于文件的路由 ↗︎,在 src/routes/api/users/+server.ts 中定义的服务端端点可在你的 SvelteKit 应用中通过 /api/users 访问。

该示例还向你展示如何在 src/app.d.ts 中配置应用范围的类型以识别你的 D1Database 绑定,将 @sveltejs/adapter-cloudflare 适配器导入 svelte.config.js,并配置它以应用于你的所有路由。

import type { RequestHandler } from "@sveltejs/kit";

export async function GET({ request, platform }) {
	try {
		let result = await platform.env.DB.prepare(
			"SELECT * FROM users LIMIT 5",
		).run();
		return new Response(JSON.stringify(result), {
			headers: { "Content-Type": "application/json" },
		});
	} catch (error) {
		return Response.json({ error: "Failed to fetch users" }, {
			status: 500
		});
	}
}
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
	namespace App {
		// interface Error {}
		// interface Locals {}
		// interface PageData {}
		interface Platform {
			env: {
				DB: D1Database;
			};
			context: {
				waitUntil(promise: Promise<any>): void;
			};
			caches: CacheStorage & { default: Cache };
		}
	}
}

export {};
import adapter from "@sveltejs/adapter-cloudflare";

export default {
	kit: {
		adapter: adapter({
			// See below for an explanation of these options
			routes: {
				include: ["/*"],
				exclude: ["<all>"],
			},
		}),
	},
};