构建一个评论 API

跳转到内容

Documentation Index
Fetch the complete documentation index at: /d1/llms.txt
Use this file to discover all available pages before exploring further.

构建一个评论 API

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

在本教程中,你将使用 D1 和 Hono ↗︎ 构建一个 JSON API,用于存储和获取博客的评论。你将创建一个 D1 数据库、定义模式,并接好读写数据库的 GET 和 POST 端点。

前置条件

  1. 注册一个 Cloudflare 账户 ↗︎。
  2. 安装 Node.js ↗︎。

Node.js 版本管理器

使用 Vite+ (vp env) ↗︎ 来安装和管理 Node.js 版本。

有关支持的 Node.js 版本,请参阅 Wrangler 系统要求。

1. 创建一个新的 Worker 项目

  1. 通过运行以下命令创建一个名为 d1-comments-api 的新项目:npmyarnpnpm

    npm create cloudflare@latest -- d1-comments-api
    
    yarn create cloudflare d1-comments-api
    
    pnpm create cloudflare@latest d1-comments-api
    

    对于设置,请选择以下选项:

    • 对于 What would you like to start with?,选择 Hello World example。
    • 对于 Which template would you like to use?,选择 Worker only。
    • 对于 Which language do you want to use?,选择 TypeScript。
    • 对于 Do you want to use git for version control?,选择 Yes。
    • 对于 Do you want to add an AGENTS.md file to help AI coding tools understand Cloudflare APIs?,选择 Yes。
    • 对于 Do you want to deploy your application?,选择 No(在部署之前我们会做一些更改)。
  2. 进入项目目录:

    cd d1-comments-api
    

2. 安装 Hono

安装 Hono ↗︎,这是一个用于在 Workers 上构建 API 的轻量级 Web 框架:

npmyarnpnpmbun

npm i hono
yarn add hono
pnpm add hono
bun add hono

3. 创建数据库

  1. 使用 Wrangler 创建一个新的 D1 数据库:

    npx wrangler@latest d1 create d1-comments-api
    
  2. 当提示 Would you like Wrangler to add it on your behalf? 时,选择 Yes。这会自动将 DB 绑定添加到你的 Wrangler 配置文件中。

    确认你的 Wrangler 配置文件包含 d1_databases 绑定以及完整的项目配置:

    {
      "$schema": "./node_modules/wrangler/config-schema.json",
      "name": "d1-comments-api",
      "main": "src/index.ts",
      "upload_source_maps": true,
      // Set this to today's date
      "compatibility_date": "2026-10-13",
      "d1_databases": [
        {
          "binding": "DB",
          "database_name": "d1-comments-api",
          "database_id": "<YOUR_DATABASE_ID>"
        }
      ]
    }
    
    name = "d1-comments-api"
    main = "src/index.ts"
    upload_source_maps = true
    # Set this to today's date
    compatibility_date = "2026-10-13"
    
    [[d1_databases]]
    binding = "DB" # available in your Worker on env.DB
    database_name = "d1-comments-api"
    database_id = "<YOUR_DATABASE_ID>"
    

    将 <YOUR_DATABASE_ID> 替换为 wrangler d1 create 命令输出的 ID。

绑定允许你的 Workers 在代码中使用变量名来访问资源,例如 D1 数据库、KV 命名空间和 R2 存储桶。你的 D1 数据库可在 Worker 中通过 env.DB 访问。

4. 创建模式并为数据库填充种子数据

  1. 创建一个内容如下的 schemas/schema.sql 文件:

    DROP TABLE IF EXISTS comments;
    CREATE TABLE IF NOT EXISTS comments (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      author TEXT NOT NULL,
      body TEXT NOT NULL,
      post_slug TEXT NOT NULL
    );
    CREATE INDEX idx_comments_post_slug ON comments (post_slug);
    
    -- Optionally, uncomment the below query to insert seed data
    -- INSERT INTO comments (author, body, post_slug) VALUES ('Kristian', 'Great post!', 'hello-world');
    
  2. 先在本地数据库上运行该模式:

    npx wrangler d1 execute d1-comments-api --local --file schemas/schema.sql
    
  3. 验证该表已在本地创建:

    npx wrangler d1 execute d1-comments-api --local --command "SELECT name FROM sqlite_schema WHERE type = 'table'"
    
    ┌──────────┐
    │ name     │
    ├──────────┤
    │ comments │
    └──────────┘
    
  4. 一旦你对模式满意,就将其应用到你的远程(生产)数据库:

    npx wrangler d1 execute d1-comments-api --remote --file schemas/schema.sql
    

5. 初始化 Hono 应用

将 src/index.ts 的内容替换为以下代码。这会设置一个带有类型化 Bindings 接口的 Hono 应用,以便 env.DB 被正确地类型化为 D1Database:

import { Hono } from "hono";

const app = new Hono();

app.get("/api/posts/:slug/comments", async (c) => {
	// Do something and return an HTTP response
	// Optionally, do something with c.req.param("slug")
});

app.post("/api/posts/:slug/comments", async (c) => {
	// Do something and return an HTTP response
	// Optionally, do something with c.req.param("slug")
});

export default app;
import { Hono } from "hono";

type Bindings = {
	DB: D1Database;
};

const app = new Hono<{ Bindings: Bindings }>();

app.get("/api/posts/:slug/comments", async (c) => {
	// Do something and return an HTTP response
	// Optionally, do something with c.req.param("slug")
});

app.post("/api/posts/:slug/comments", async (c) => {
	// Do something and return an HTTP response
	// Optionally, do something with c.req.param("slug")
});

export default app;

6. 查询评论

为 GET 端点添加逻辑,以获取给定文章(post)的评论。这里使用 D1 的 Workers Binding API 来准备并执行一个参数化查询:

app.get("/api/posts/:slug/comments", async (c) => {
	const { slug } = c.req.param();
	const { results } = await c.env.DB.prepare(
		"SELECT * FROM comments WHERE post_slug = ?",
	)
		.bind(slug)
		.run();
	return c.json(results);
});
app.get("/api/posts/:slug/comments", async (c) => {
	const { slug } = c.req.param();
	const { results } = await c.env.DB.prepare(
		"SELECT * FROM comments WHERE post_slug = ?",
	)
		.bind(slug)
		.run();
	return c.json(results);
});

该代码使用 prepare 创建一个参数化语句,使用 bind 安全地传入 slug 值(防止 SQL 注入),并使用 run 执行查询。

7. 插入评论

添加 POST 端点以创建新评论。这会在插入一行之前验证请求正文:

app.post("/api/posts/:slug/comments", async (c) => {
	const { slug } = c.req.param();
	const { author, body } = await c.req.json();

	if (!author) return c.text("Missing author value for new comment", 400);
	if (!body) return c.text("Missing body value for new comment", 400);

	const { success } = await c.env.DB.prepare(
		"INSERT INTO comments (author, body, post_slug) VALUES (?, ?, ?)",
	)
		.bind(author, body, slug)
		.run();

	if (success) {
		c.status(201);
		return c.text("Created");
	} else {
		c.status(500);
		return c.text("Something went wrong");
	}
});
app.post("/api/posts/:slug/comments", async (c) => {
	const { slug } = c.req.param();
	const { author, body } = await c.req.json<{
		author: string;
		body: string;
	}>();

	if (!author) return c.text("Missing author value for new comment", 400);
	if (!body) return c.text("Missing body value for new comment", 400);

	const { success } = await c.env.DB.prepare(
		"INSERT INTO comments (author, body, post_slug) VALUES (?, ?, ?)",
	)
		.bind(author, body, slug)
		.run();

	if (success) {
		c.status(201);
		return c.text("Created");
	} else {
		c.status(500);
		return c.text("Something went wrong");
	}
});

8.(可选)添加 CORS 支持

如果你计划从不同源的前端应用调用此 API,请添加 CORS 中间件。从 Hono 导入 cors 模块,并将其添加到你的路由之前:

import { Hono } from "hono";
import { cors } from "hono/cors";

const app = new Hono();
app.use("/api/*", cors());
import { Hono } from "hono";
import { cors } from "hono/cors";

type Bindings = {
	DB: D1Database;
};

const app = new Hono<{ Bindings: Bindings }>();
app.use("/api/*", cors());

当你向 /api/* 发起请求时,Hono 会自动生成 CORS 头并将其添加到你的 API 响应中。

9. 部署你的应用

  1. 登录你的 Cloudflare 账户(如果你尚未登录):

    npx wrangler whoami
    

    如果你尚未登录,Wrangler 会提示你登录。

  2. 部署你的 Worker:

    npx wrangler deploy
    
  3. 通过插入一条评论然后获取它来测试 API:

    # Replace <YOUR_SUBDOMAIN> with your workers.dev subdomain
    curl -X POST https://d1-comments-api.<YOUR_SUBDOMAIN>.workers.dev/api/posts/hello-world/comments \
      -H "Content-Type: application/json" \
      -d '{"author": "Kristian", "body": "Great post!"}'
    
    Created
    
    curl https://d1-comments-api.<YOUR_SUBDOMAIN>.workers.dev/api/posts/hello-world/comments
    
    [
      {
        "id": 1,
        "author": "Kristian",
        "body": "Great post!",
        "post_slug": "hello-world"
      }
    ]
    

完整示例

包含所有路由和 CORS 支持的完整 src/index.ts:

import { Hono } from "hono";
import { cors } from "hono/cors";

const app = new Hono();
app.use("/api/*", cors());

app.get("/api/posts/:slug/comments", async (c) => {
	const { slug } = c.req.param();
	const { results } = await c.env.DB.prepare(
		"SELECT * FROM comments WHERE post_slug = ?",
	)
		.bind(slug)
		.run();
	return c.json(results);
});

app.post("/api/posts/:slug/comments", async (c) => {
	const { slug } = c.req.param();
	const { author, body } = await c.req.json();

	if (!author) return c.text("Missing author value for new comment", 400);
	if (!body) return c.text("Missing body value for new comment", 400);

	const { success } = await c.env.DB.prepare(
		"INSERT INTO comments (author, body, post_slug) VALUES (?, ?, ?)",
	)
		.bind(author, body, slug)
		.run();

	if (success) {
		c.status(201);
		return c.text("Created");
	} else {
		c.status(500);
		return c.text("Something went wrong");
	}
});

export default app;
import { Hono } from "hono";
import { cors } from "hono/cors";

type Bindings = {
	DB: D1Database;
};

const app = new Hono<{ Bindings: Bindings }>();
app.use("/api/*", cors());

app.get("/api/posts/:slug/comments", async (c) => {
	const { slug } = c.req.param();
	const { results } = await c.env.DB.prepare(
		"SELECT * FROM comments WHERE post_slug = ?",
	)
		.bind(slug)
		.run();
	return c.json(results);
});

app.post("/api/posts/:slug/comments", async (c) => {
	const { slug } = c.req.param();
	const { author, body } = await c.req.json<{
		author: string;
		body: string;
	}>();

	if (!author) return c.text("Missing author value for new comment", 400);
	if (!body) return c.text("Missing body value for new comment", 400);

	const { success } = await c.env.DB.prepare(
		"INSERT INTO comments (author, body, post_slug) VALUES (?, ?, ?)",
	)
		.bind(author, body, slug)
		.run();

	if (success) {
		c.status(201);
		return c.text("Created");
	} else {
		c.status(500);
		return c.text("Something went wrong");
	}
});

export default app;

后续步骤