任务:用 Hono 写 API 服务,通过 @hono/node-server 适配器,让 API 服务跑在 Node.js 原生的 HTTP 服务器上。
第一步, 环境是node.js,安装环境。去官网下载node.js软件就好了
第二步, 创建目录,mkdir my-api 进入目录,cd my-api 初始化项目,npm init -y 安装适配器,npm install hono @hono/node-server
其他(可选) 如果使用TypeScript语言写,还需要安装 tsx 、typescript、类型声明文件: npm install -D typescript tsx @types/node
说明 typescript 是编译器,typescript 包提供了 tsc 命令,它就是真正把 .ts 编译成 .js 的编译器。过程中做了两件事1、类型检查 2、转译/编译
tsx 是一个运行器,它让你能直接运行 TS 文件,而不需要先手动编译。开发时直接跑 .ts 文件,底层用 esbuild 转译,快,但不做类型检查。
@types/node不是工具,是类型声明文件。是社区维护的Node.js API 的类型描述。它只在开发/编译阶段用来做类型检查,运行时根本不需要。
-D 说明放在devDependencies,只在开发/编译阶段用。
第三步, 创建文件 index.ts 在文件 index.ts里面编写 API 服务代码
typescript
// 引入hono和 hono的node适配器
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
// 1. 创建 Hono 应用实例
const app = new Hono()
// 2. 定义一个简单的 GET 接口,返回文本
app.get('/', (c) => {
return c.text('Hono API is running on Node.js!')
})
// 3. 定义一个返回 JSON 的接口
app.get('/api/hello', (c) => {
return c.json({
message: 'Hello from Hono!',
timestamp: new Date().toISOString(),
})
})
// 4. 带路径参数的 GET 接口
app.get('/api/users/:id', (c) => {
const userId = c.req.param('id')
return c.json({
id: userId,
name: `User ${userId}`,
email: `user${userId}@example.com`,
})
})
// 5. 处理 POST 请求,解析 JSON 请求体
app.post('/api/users', async (c) => {
const body = await c.req.json()
return c.json(
{
message: 'User created successfully',
user: body,
},
201 // 状态码
)
})
// 6. 启动服务器
const port = 3000
console.log(`Server is running on http://localhost:${port}`)
serve({
fetch: app.fetch,
port,
})
第四步启动服务
为了简便,package.json 中加一行启动脚本
js
{
"scripts": {
"dev": "tsx index.ts"
}
}
启动服务、npm run dev
也可以,npm run tsx index.ts
第五步测试服务
bash
# 测试根路径
curl http://localhost:3000/
# 测试 JSON 接口
curl http://localhost:3000/api/hello
# 测试路径参数
curl http://localhost:3000/api/users/42
# 测试 POST 请求
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"张三","email":"zhangsan@example.com"}'
后续在index.ts 文件上面 用hono规范 继续修改为不同的API路由逻辑。