当前位置: 首页 > news >正文

hono+postgresql+CURD

  • 数据库: PostgreSQL
  • 用户名: postgres
  • 密码: 123

第一步:环境准备

在开始之前,请确保你的电脑上已经安装了以下软件:

  • Node.js: 版本 18 或更高。
  • PostgreSQL: 确保 PostgreSQL 服务已经安装并正在运行。

你可以使用 node -v 和 psql --version 来检查它们是否已正确安装。


第二步:数据库和数据表设置

我们需要先创建一个数据库和一个用于存放用户数据的表。

登录 PostgreSQL:
打开你的终端或命令行工具,使用 psql 命令登录到 PostgreSQL。你可能需要根据你的安装方式指定用户。

  • Generated bash
psql -U postgres

Use code with caution.Bash

创建数据库:
我们将创建一个名为 hono_db 的数据库。

  • Generated sql
CREATE DATABASE hono_db;

Use code with caution.SQL

连接到新数据库:
使用 \c 命令连接到刚刚创建的数据库。

  • Generated sql
\c hono_db

Use code with caution.SQL

创建用户表 (users):
我们将创建一个 users 表,包含 id, name, 和 email 字段。

  • Generated sql
CREATE TABLE users (id SERIAL PRIMARY KEY,name VARCHAR(100) NOT NULL,email VARCHAR(100) UNIQUE NOT NULL,created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

Use code with caution.SQL

    • SERIAL PRIMARY KEY: 自动递增的整数作为主键。
    • VARCHAR(100): 存储姓名和邮箱。
    • NOT NULL 和 UNIQUE: 确保数据的完整性。
    • created_at: 记录创建时间。

现在数据库已经准备好了。


第三步:项目初始化与依赖安装

创建项目文件夹:

  • Generated bash
mkdir hono-postgres-crud
cd hono-postgres-crud

Use code with caution.Bash

初始化 Node.js 项目:

  • Generated bash
npm init -y

Use code with caution.Bash

安装 Hono 和相关依赖:

    • hono: Hono 核心库。
    • @hono/node-server: 在 Node.js 环境中运行 Hono 的适配器。
    • pg: Node.js 的 PostgreSQL 客户端库,用于连接和查询数据库。
    • dotenv: 用于管理环境变量(如数据库密码),这是最佳实践。
  • Generated bash
npm install hono @hono/node-server pg dotenv

Use code with caution.Bash

安装开发依赖 (TypeScript):
我们将使用 TypeScript 来编写代码,这能提供更好的类型安全和开发体验。

    • typescript: TypeScript 编译器。
    • tsx: 一个非常快速的 TypeScript 执行器,用于开发。
    • @types/...: 对应库的类型定义文件。
  • Generated bash
npm install -D typescript @types/node @types/pg tsx

Use code with caution.Bash


第四步:项目配置

配置 TypeScript (tsconfig.json):
在项目根目录创建 tsconfig.json 文件,并添加以下内容:

  • Generated json
{"compilerOptions": {"target": "ESNext","module": "ESNext","moduleResolution": "node","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"outDir": "./dist"}
}

Use code with caution.Json

配置环境变量 (.env 文件):
在项目根目录创建 .env 文件。不要将此文件提交到 Git 仓库。我们在这里存放数据库连接信息。

  • Generated code
# PostgreSQL Connection String
# 格式: postgresql://[user]:[password]@[host]:[port]/[database]
DATABASE_URL="postgresql://postgres:123@localhost:5432/hono_db"

Use code with caution.

注意:

    • 请将 postgresql:123 替换成你自己的用户名和密码。
    • localhost:5432 是 PostgreSQL 的默认主机和端口。
    • hono_db 是我们在第二步中创建的数据库名。

添加 package.json 脚本:
打开 package.json 文件,在 "scripts" 部分添加一个 dev 命令,以便用 tsx 启动开发服务器。

  • Generated json
"scripts": {"dev": "tsx --watch src/index.ts"
},

Use code with caution.Json


第五步:编写 Hono 应用代码

创建 src 目录和 index.ts 文件:

  • Generated bash
mkdir src
touch src/index.ts

Use code with caution.Bash

编写 src/index.ts 文件:
这是我们项目的核心文件。我们将在这里设置 Hono 应用、连接数据库并定义所有 CRUD 路由。

  • Generated typescript
import { Hono } from 'hono';
import { logger } from 'hono/logger';
import { serve } from '@hono/node-server';
import { Pool } from 'pg';
import 'dotenv/config'; // 自动加载 .env 文件// 1. 初始化 Hono 应用
const app = new Hono();// 2. 初始化 PostgreSQL 连接池
const pool = new Pool({connectionString: process.env.DATABASE_URL,
});// 检查数据库连接
pool.connect((err, client, release) => {if (err) {return console.error('Error acquiring client', err.stack);}console.log('Successfully connected to PostgreSQL!');client.release();
});// 3. 中间件
app.use('*', logger());// 定义 User 类型 (用于 TypeScript)
type User = {id: number;name: string;email: string;
};// 4. 定义 CRUD 路由// CREATE: 创建一个新用户
app.post('/users', async (c) => {try {const { name, email } = await c.req.json<{ name: string; email: string }>();if (!name || !email) {return c.json({ error: 'Name and email are required' }, 400);}const result = await pool.query('INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',[name, email]);const newUser: User = result.rows[0];return c.json(newUser, 201); // 201 Created} catch (error) {console.error('Create user error:', error);return c.json({ error: 'Failed to create user' }, 500);}
});// READ: 获取所有用户
app.get('/users', async (c) => {try {const result = await pool.query('SELECT * FROM users ORDER BY id ASC');const users: User[] = result.rows;return c.json(users);} catch (error) {console.error('Get all users error:', error);return c.json({ error: 'Failed to fetch users' }, 500);}
});// READ: 获取单个用户
app.get('/users/:id', async (c) => {try {const id = parseInt(c.req.param('id'));const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);if (result.rows.length === 0) {return c.json({ error: 'User not found' }, 404);}const user: User = result.rows[0];return c.json(user);} catch (error) {console.error('Get single user error:', error);return c.json({ error: 'Failed to fetch user' }, 500);}
});// UPDATE: 更新一个用户
app.put('/users/:id', async (c) => {try {const id = parseInt(c.req.param('id'));const { name, email } = await c.req.json<{ name: string; email: string }>();if (!name || !email) {return c.json({ error: 'Name and email are required' }, 400);}const result = await pool.query('UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING *',[name, email, id]);if (result.rows.length === 0) {return c.json({ error: 'User not found' }, 404);}const updatedUser: User = result.rows[0];return c.json(updatedUser);} catch (error) {console.error('Update user error:', error);return c.json({ error: 'Failed to update user' }, 500);}
});// DELETE: 删除一个用户
app.delete('/users/:id', async (c) => {try {const id = parseInt(c.req.param('id'));const result = await pool.query('DELETE FROM users WHERE id = $1 RETURNING *', [id]);if (result.rowCount === 0) {return c.json({ error: 'User not found' }, 404);}return c.json({ message: `User with id ${id} deleted successfully` });} catch (error) {console.error('Delete user error:', error);return c.json({ error: 'Failed to delete user' }, 500);}
});// 5. 启动服务器
const port = 3000;
console.log(`Server is running on port ${port}`);serve({fetch: app.fetch,port,
});

Use code with caution.TypeScript


第六步:运行和测试应用

启动开发服务器:
在你的终端中,运行以下命令:

  • Generated bash
npm run dev

Use code with caution.Bash

如果一切顺利,你会看到如下输出:

Generated code

Successfully connected to PostgreSQL!
Server is running on port 3000

Use code with caution.

  • 使用 curl 或 Postman 测试 API:
    打开另一个终端,使用 curl 命令来测试你的 CRUD 端点。

CREATE (创建用户)

    • Generated bash
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "email": "alice@example.com"}'

Use code with caution.Bash

你应该会收到类似 {"id":1,"name":"Alice","email":"alice@example.com"} 的响应。

再创建一个用户:

Generated bash

curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name": "Bob", "email": "bob@example.com"}'

Use code with caution.Bash

READ (获取所有用户)

    • Generated bash
curl http://localhost:3000/users

Use code with caution.Bash

你应该会看到一个包含 Alice 和 Bob 的 JSON 数组。

READ (获取单个用户)
假设 Alice 的 ID 是 1。

    • Generated bash
curl http://localhost:3000/users/1

Use code with caution.Bash

你应该会只看到 Alice 的信息。

UPDATE (更新用户)
更新 ID 为 1 的用户的信息。

    • Generated bash
curl -X PUT http://localhost:3000/users/1 \
-H "Content-Type: application/json" \
-d '{"name": "Alice Smith", "email": "alice.smith@example.com"}'

Use code with caution.Bash

你应该会收到更新后的用户信息。

DELETE (删除用户)
删除 ID 为 2 的用户 (Bob)。

    • Generated bash
curl -X DELETE http://localhost:3000/users/2

Use code with caution.Bash

你应该会收到 {"message":"User with id 2 deleted successfully"}。

再次检查
再次获取所有用户,确认 Bob 已经被删除。

    • Generated bash
curl http://localhost:3000/users

Use code with caution.Bash


第七步:总结与后续步骤

恭喜!你已经成功创建了一个使用 Hono.js 和 PostgreSQL 的全功能 CRUD API。

后续可以优化的方向:

  • 输入验证: 使用 @hono/zod-validator 和 Zod 库来验证请求体,确保传入的数据格式正确。
  • 错误处理: 创建一个全局的错误处理中间件来统一处理和格式化错误响应。
  • 代码结构: 当项目变大时,可以将路由、数据库逻辑(也称为 Repository 或 Service 层)分离到不同的文件中,使代码更易于维护。
  • 使用 ORM: 对于更复杂的项目,可以考虑使用像 Drizzle ORM 或 Prisma 这样的 ORM,它们可以简化数据库操作并提供更强的类型安全。

CRUD.http

// 创建用户
POST http://localhost:8080/users
Content-Type: application/json{"name": "Bob1","email": "bob1@example.com"
}###
// 获取所有用户
GET http://localhost:8080/users###
// 获取单个用户
GET http://localhost:8080/users/5###
// 更新用户
PUT http://localhost:8080/users/5
Content-Type: application/json{"name": "Bob2","email": "bob2@example.com"
}###
// 删除用户
DELETE http://localhost:8080/users/1

http://www.dtcms.com/a/263346.html

相关文章:

  • 华为云Flexus+DeepSeek征文 | 从零开始搭建Dify-LLM应用开发平台:华为云全流程单机部署实战教程
  • FPGA实现CameraLink视频解码转SDI输出,基于LVDS+GTX架构,提供2套工程源码和技术支持
  • 如何让Excel自动帮我们算加减乘除?
  • Python 数据分析与机器学习入门 (一):环境搭建与核心库概览
  • DAY 43 预训练模型
  • RWKV-8 系列之 DeepEmbedAttention:精简 KV 缓存,尤其适合混合模型(RWKV-7s)
  • 创客匠人方法论:从 0 到 1 打造创始人 IP 的实战框架
  • pytorch底层原理学习--PyTorch 架构梳理
  • 3.前端和后端参数不一致,后端接不到数据的解决方案
  • 16014.rtsp推流服务器
  • 详解Kafka如何保证消息可靠性
  • 大语言模型(LLM)笔记
  • YOLOv12_ultralytics-8.3.145_2025_5_27部分代码阅读笔记-instance.py
  • [15-2] 读写内部FLASH读取芯片ID 江协科技学习笔记(20个知识点)
  • MySQL DATETIME 类型时间精度陷阱:一次由毫秒引发的数据“消失”之谜
  • 【Actix Web】Rust Web开发实战:Actix Web框架全面指南(2025企业级应用版)
  • java初学习(-2025.6.30小总结)
  • TCP 三次握手协商 MSS 前,如何确定 MSS 值
  • SQL规范
  • 【软考高项论文】论信息系统项目的范围管理
  • 剑指offer51_数组中数值和下标相等的元素
  • 机器人仿真(1)Ubuntu24.04下CLion的ROS2开发环境配置
  • [ C++ ] | unordered_map 底层实现原理
  • Linux-进程概念(1)
  • 亚马逊,塔吉特采购,测评防砍单封号的养号下单黄金法则
  • 华为云Flexus+DeepSeek征文 | Word办公软件接入华为云ModelArts Studio大模型,实现AI智能办公
  • 【C++指南】C++ list容器完全解读(三):list迭代器的实现与优化
  • Deploy StarRocks with Docker
  • ubuntu源码安装python3.13遇到Could not build the ssl module!解决方法
  • Deepoc 大模型在无人机行业应用效果的方法