文章目录
-
-
- 结构
- demo步骤
- demo运行效果
- API测试
-
- [(1) 添加待办事项](#(1) 添加待办事项)
- [(2) 获取所有待办事项](#(2) 获取所有待办事项)
- [(3) 切换完成状态](#(3) 切换完成状态)
- [(4) 删除待办事项](#(4) 删除待办事项)
- API测试-RESTClient一些其他的高级功能
-
- 环境变量管理不同环境配置
- [授权认证 测试需要登录的接口](#授权认证 测试需要登录的接口)
- 保存响应
- 测试脚本编写自动化测试
- bug解决
-
结构
尝试写一个简单的待办事项(Todo)管理的NodeJs后端服务,文件架构如下:
js
zyxTest/
├── server.js # 主程序
├── package.json # 项目配置
└── .gitignore # 忽略文件

demo步骤
-
初始化项目并安装依赖:
express框架似乎是nodejs写小程序的常用框架,我们先用express进行尝试
bash
npm init -y
#需要首先在windows powershell里面运行 Set-ExecutionPolicy RemoteSigned -Scope CurrentUser不然会弹出vscode禁止运行脚本
npm install express
- 创建
server.js
js
const express = require('express');
const app = express();
app.use(express.json());
// 模拟数据库(内存存储)
let todos = [];
let idCounter = 1;
// 获取所有待办事项
app.get('/todos', (req, res) => {
res.json(todos);
});
// 添加新待办事项
app.post('/todos', (req, res) => {
const { title } = req.body;
if (!title) {
return res.status(400).json({ error: 'Title is required' });
}
const newTodo = { id: idCounter++, title, completed: false };
todos.push(newTodo);
res.status(201).json(newTodo);
});
// 删除待办事项
app.delete('/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
todos = todos.filter(todo => todo.id !== id);
res.sendStatus(204);
});
// 切换完成状态
app.patch('/todos/:id/toggle', (req, res) => {
const id = parseInt(req.params.id);
const todo = todos.find(t => t.id === id);
if (todo) {
todo.completed = !todo.completed;
res.json(todo);
} else {
res.status(404).json({ error: 'Todo not found' });
}
});
// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
-
vscode终端启动服务器:
node server.js
demo运行效果
此时vscode终端会给出访问链接:

点击链接可以看到前端状态,此处采用了最简单的写法

API测试
我们最初采用curl进行api测试,但win里面的curl不太好用(详情见bug解决第三条)改用vscode的RestClient插件进行api测试。
这个插件能帮助我们发送写好的http请求,效果类似postman
插件效果如下,红框内部是模拟请求发送按钮。

(1) 添加待办事项
curl方法:
bash
curl -X POST http://localhost:3000/todos \
-H "Content-Type: application/json" \
-d '{"title": "Buy milk"}'
使用插件编写test.http方法:
http
POST http://localhost:3000/todos
Content-Type: application/json
{
"title": "使用 REST Client 测试"
}
获取到响应,测试成功

(2) 获取所有待办事项
bash
curl http://localhost:3000/todos
http
### 获取待办事项
GET http://localhost:3000/todos
响应如下,测试成功:

(3) 切换完成状态
bash
curl -X PATCH http://localhost:3000/todos/1/toggle
http
PATCH http://localhost:3000/todos/1/toggle
响应如下,测试成功:

(4) 删除待办事项
bash
curl -X DELETE http://localhost:3000/todos/1
http
### 删除待办事项 (DELETE)
DELETE http://localhost:3000/todos/1

也可以通过@name add_todo,使用 # @name 请求名称
语法为请求命名,后续引用响应,可以切换单独某个请求的完成状态:
http
### 1. 添加新待办事项并命名请求
# @name add_todo
POST http://localhost:3000/todos
Content-Type: application/json
{
"title": "使用变量示例的任务"
}
### 2. 从响应中提取ID并赋值给变量
@todoId = {{add_todo.response.body.id}}
### 3. 切换完成状态(使用变量)
PATCH http://localhost:3000/todos/{{todoId}}/toggle
### 4. 删除待办事项(使用同一个变量)
DELETE http://localhost:3000/todos/{{todoId}}

API测试-RESTClient一些其他的高级功能
环境变量管理不同环境配置
http
### 设置变量
@dev = http://localhost:3000
@prod = https://api.yourserver.com
### 使用变量
GET {{dev}}/todos
授权认证 测试需要登录的接口
http
POST http://localhost:3000/login
Content-Type: application/json
{
"username": "admin",
"password": "123456"
}
### 获取token后使用
@token = {{login.response.body.token}}
GET http://localhost:3000/profile
Authorization: Bearer {{token}}
保存响应
http
GET http://localhost:3000/todos
>> response.json
测试脚本编写自动化测试
http
GET http://localhost:3000/todos
> {%
client.test("Status OK", function() {
client.assert(response.status === 200);
});
client.test("Has items", function() {
client.assert(response.body.length > 0);
});
%}
bug解决
-
端口占用:
bash# 查找占用3000端口的进程 netstat -ano | findstr :3000 #mac似乎是lsof -i :3000 # 终止进程 taskkill /PID <PID> /F #mac是kill -9
-
依赖安装失败:
尝试清除缓存
bashnpm cache clean --force rm -rf node_modules package-lock.json npm install
-
windows的curl问题:
在 Windows PowerShell 中,
curl
命令实际上是Invoke-WebRequest
cmdlet 的别名,所以我们在win下直接用curl会报错:
win下可以直接使用 PowerShell 原生命令进行测试:
bash
Invoke-RestMethod -Uri http://localhost:3000/todos `
-Method POST `
-Headers @{"Content-Type"="application/json"} `
-Body '{"title":"新任务"}'
但是还是比较建议在 VSCode 中用 REST Client 扩展,更加方便
- 创建
test.http
文件 - 添加内容:
http
### 添加待办事项
POST http://localhost:3000/todos
Content-Type: application/json
{
"title": "使用 REST Client 测试"
}
### 获取待办事项
GET http://localhost:3000/todos
再点击每个请求上方的 "Send Request",就是发送请求
