在本教程中,你将学习如何创建 Cloudflare Workers 应用,并使用 TCP Sockets 和 Hyperdrive 连接到 PostgreSQL 数据库。你在本教程中创建的 Workers 应用将与 PostgreSQL 中的产品数据库交互。
要继续,请:
- 若尚未注册,请注册 Cloudflare 账户 ↗。
- 安装
npm↗。 - 安装
Node.js↗。使用 Volta ↗ 或 nvm ↗ 等 Node 版本管理器以避免权限问题并切换 Node.js 版本。Wrangler 需要 Node 版本16.17.0或更高。 - 确保你可以访问 PostgreSQL 数据库。
首先,使用 create-cloudflare CLI ↗ 创建新的 Worker 应用。打开终端窗口并运行以下命令:
npm create cloudflare@latest -- postgres-tutorialyarn create cloudflare postgres-tutorialpnpm create cloudflare@latest postgres-tutorial这将提示你安装 create-cloudflare ↗ 包并引导你完成设置向导。
进行设置时,请选择以下选项:
- 对于 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 deploy your application?,选择
No(部署前我们还会做一些修改)。
若选择部署,系统将要求你进行身份验证(若尚未登录),项目将被部署。即使已部署,你仍可在本教程结束时修改 Worker 代码并再次部署。
现在,进入新创建的目录:
cd postgres-tutorial数据库驱动程序(包括 Postgres.js)需要 Node.js 兼容性,必须为你的 Workers 项目进行配置。
要为 Worker 或 Pages 项目启用内置运行时 API 和 polyfill,请在你的 Wrangler 配置文件中添加 nodejs_compat 兼容性标志,并将兼容性日期设置为 2024 年 9 月 23 日或更高版本。这将为 Workers 项目启用 Node.js 兼容性。
{
"compatibility_flags": [
"nodejs_compat"
],
// Set this to today's date
"compatibility_date": "2026-08-17"
}compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"要连接到 PostgreSQL 数据库,你需要 pg 库。在 Worker 应用目录中运行以下命令安装该库:
npm i pgyarn add pgpnpm add pgbun add pg接下来,安装 pg 库的 TypeScript 类型,以便在 TypeScript 代码中启用类型检查和自动补全:
npm i -D @types/pgyarn add -D @types/pgpnpm add -D @types/pgbun add -d @types/pg选择以下两种方法之一连接 PostgreSQL 数据库:
连接字符串包含连接数据库所需的全部信息。它是一个 URL,包含以下信息:
postgresql://username:password@host:port/database将 username、password、host、port 和 database 替换为 PostgreSQL 数据库的相应值。
将连接字符串设置为密钥(secret),以免以明文存储。使用 wrangler secret put 并指定示例变量名 DB_URL:
npx wrangler secret put DB_URL➜ wrangler secret put DB_URL
-------------------------------------------------------
? Enter a secret value: › ********************
✨ Success! Uploaded secret DB_URL在 .dev.vars 文件中本地设置 DB_URL secret,如使用 Secrets 进行本地开发中所述。
DB_URL="<ENTER YOUR POSTGRESQL CONNECTION STRING>"通过 Cloudflare 仪表板或 Wrangler 配置文件,将每个数据库参数配置为环境变量。参考 Wrangler 配置文件配置示例:
{
"vars": {
"DB_USERNAME": "postgres",
// Set your password by creating a secret so it is not stored as plain text
"DB_HOST": "ep-aged-sound-175961.us-east-2.aws.neon.tech",
"DB_PORT": 5432,
"DB_NAME": "productsdb"
}
}[vars]
DB_USERNAME = "postgres"
DB_HOST = "ep-aged-sound-175961.us-east-2.aws.neon.tech"
DB_PORT = 5_432
DB_NAME = "productsdb"要将密码设置为密钥(secret)以免以明文存储,请使用 wrangler secret put。DB_PASSWORD 是 Worker 中访问此 secret 的示例变量名:
npx wrangler secret put DB_PASSWORD-------------------------------------------------------
? Enter a secret value: › ********************
✨ Success! Uploaded secret DB_PASSWORD打开 Worker 的主文件(例如 worker.ts),从 pg 库导入 Client 类:
import { Client } from "pg";在 fetch 事件处理程序中,使用你选择的方法连接 PostgreSQL 数据库——连接字符串或显式参数。
// create a new Client instance using the connection string
const sql = new Client({ connectionString: env.DB_URL });
// connect to the PostgreSQL database
await sql.connect();// create a new Client instance using explicit parameters
const sql = new Client({
username: env.DB_USERNAME,
password: env.DB_PASSWORD,
host: env.DB_HOST,
port: env.DB_PORT,
database: env.DB_NAME,
ssl: true, // Enable SSL for secure connections
});
// connect to the PostgreSQL database
await sql.connect();为演示如何与产品数据库交互,你将在收到请求时查询 products 表以获取数据。
将 worker.ts 文件中的现有代码替换为以下代码:
import { Client } from "pg";
export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a new Client instance using the connection string
// or explicit parameters as shown in the previous steps.
// Here, we are using the connection string method.
const sql = new Client({
connectionString: env.DB_URL,
});
// Connect to the PostgreSQL database
await sql.connect();
// Query the products table
const result = await sql.query("SELECT * FROM products");
// Return the result as JSON
return new Response(JSON.stringify(result.rows), {
headers: {
"Content-Type": "application/json",
},
});
},
} satisfies ExportedHandler<Env>;此代码在 Worker 应用内建立与 PostgreSQL 数据库的连接,查询 products 表,并将结果作为 JSON 响应返回。
运行以下命令部署 Worker:
npx wrangler deploy你的应用现已上线,可通过 <YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev 访问。
部署后,你可以使用 Cloudflare Worker 与 PostgreSQL 产品数据库交互。每当向 Worker 的 URL 发起请求时,将从 products 表获取数据并以 JSON 响应返回。你可以根据需要修改查询以从产品数据库检索所需数据。
要向 products 表插入新行,在 Worker 中创建处理 POST 请求的新 API 端点。收到带有 JSON 负载的 POST 请求时,Worker 将使用提供的数据向 products 表插入新行。
假设 products 表包含以下列:id、name、description 和 price。
在 worker.ts 文件的 fetch 事件处理程序内、现有查询代码之前添加以下代码片段:
import { Client } from "pg";
export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a new Client instance using the connection string
// or explicit parameters as shown in the previous steps.
// Here, we are using the connection string method.
const sql = new Client({
connectionString: env.DB_URL,
});
// Connect to the PostgreSQL database
await sql.connect();
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/products") {
// Parse the request's JSON payload
const productData = (await request.json()) as {
name: string;
description: string;
price: number;
};
const name = productData.name,
description = productData.description,
price = productData.price;
// Insert the new product into the products table
const insertResult = await sql.query(
`INSERT INTO products(name, description, price) VALUES($1, $2, $3)
RETURNING *`,
[name, description, price],
);
// Return the inserted row as JSON
return new Response(JSON.stringify(insertResult.rows), {
headers: { "Content-Type": "application/json" },
});
}
// Query the products table
const result = await sql.query("SELECT * FROM products");
// Return the result as JSON
return new Response(JSON.stringify(result.rows), {
headers: {
"Content-Type": "application/json",
},
});
},
} satisfies ExportedHandler<Env>;此代码片段执行以下操作:
- 检查请求是否为
POST请求且 URL 路径为/products。 - 解析请求中的 JSON 负载。
- 使用提供的产品数据构造
INSERTSQL 查询。 - 执行查询,向
products表插入新行。 - 将插入的行作为 JSON 响应返回。
现在,当你向 Worker 的 URL 发送带有 /products 路径和 JSON 负载的 POST 请求时,Worker 将使用提供的数据向 products 表插入新行。当向 / 发起请求时,Worker 将返回数据库中的所有产品。
完成这些更改后,通过运行以下命令再次部署 Worker:
npx wrangler deploy你现在可以使用 Cloudflare Worker 向 products 表插入新行。要测试此功能,向 Worker 的 URL 发送带有 /products 路径和包含新产品数据的 JSON 负载的 POST 请求:
{
"name": "Sample Product",
"description": "This is a sample product",
"price": 19.99
}你已成功创建连接 PostgreSQL 数据库并处理从产品表获取数据和插入新行的 Cloudflare Worker。
使用 PostgreSQL 数据库的连接字符串创建 Hyperdrive 配置。
npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name" --caching-disabled此命令输出 Hyperdrive 配置 id,将用于 Hyperdrive 绑定(binding)。通过在 Wrangler 配置文件中指定 id 设置绑定。
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "hyperdrive-example",
"main": "src/index.ts",
// Set this to today's date
"compatibility_date": "2026-08-17",
"compatibility_flags": [
"nodejs_compat"
],
// Pasted from the output of `wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string=[...]` above.
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"
}
]
}"$schema" = "./node_modules/wrangler/config-schema.json"
name = "hyperdrive-example"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-08-17"
compatibility_flags = [ "nodejs_compat" ]
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"使用以下命令创建 Hyperdrive 绑定的类型:
npx wrangler types在 Worker 代码中将现有连接字符串替换为 Hyperdrive 连接字符串。
export default {
async fetch(request, env, ctx): Promise<Response> {
const sql = new Client({connectionString: env.HYPERDRIVE.connectionString})
const url = new URL(request.url);
//rest of the routes and database queries
},
} satisfies ExportedHandler<Env>;运行以下命令部署 Worker:
npx wrangler deploy你的 Worker 应用现已上线,可通过 <YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev 访问,并使用 Hyperdrive。Hyperdrive 通过在全球范围池化连接并缓存请求来加速数据库查询。
要基于数据库和 Workers 构建更多内容,请参阅教程并探索数据库文档。
如有疑问、需要帮助或想分享你的项目,请加入 Cloudflare 开发者社区 Discord ↗,与其他开发者和 Cloudflare 团队交流。