RESTful API 测试和调试
使用工具测试 API
1. Postman 测试
Postman 是最流行的 API 测试工具,就像是 API 的"试验场"。
Postman 官网地址:https://www.postman.com/。
基本测试步骤:
- 创建新请求
- 设置 HTTP 方法(GET、POST 等)
- 输入 API 地址
- 添加请求头和请求体
- 发送请求查看响应
Postman 集合示例:
{ "info": { "name": "用户管理 API 测试", "description": "测试用户相关的所有 API 端点" }, "item": [ { "name": "获取用户列表", "request": { "method": "GET", "header": [], "url": { "raw": "{{baseUrl}}/api/users?page=1&limit=10", "host": ["{{baseUrl}}"], "path": ["api", "users"], "query": [ {"key": "page", "value": "1"}, {"key": "limit", "value": "10"} ] } } } ] }
2. curl 命令行测试
# 获取用户列表 curl -X GET "https://api.example.com/users" \ -H "Content-Type: application/json" # 创建新用户 curl -X POST "https://api.example.com/users" \ -H "Content-Type: application/json" \ -d '{ "name": "张三", "email": "zhangsan@example.com" }' # 更新用户信息 curl -X PUT "https://api.example.com/users/123" \ -H "Content-Type: application/json" \ -d '{ "name": "李四", "email": "lisi@example.com" }' # 删除用户 curl -X DELETE "https://api.example.com/users/123" \ -H "Content-Type: application/json"
3. 浏览器开发者工具
// 在浏览器控制台中测试 fetch('/api/users', { method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
常见问题调试
1. CORS 跨域问题
报错信息:
Access to fetch at 'https://api.example.com/users' from origin 'http://localhost:3000' has been blocked by CORS policy
解决方案:
// 服务器端需要设置 CORS 头 app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); });
2. 状态码错误
常见错误及原因:
状态码 | 可能原因 | 解决方法 |
---|---|---|
400 | 请求数据格式错误 | 检查 JSON 格式和必填字段 |
401 | 身份验证失败 | 检查 Token 是否正确 |
404 | API 路径错误 | 确认 URL 拼写正确 |
500 | 服务器内部错误 | 查看服务器日志 |
3. 数据格式问题
// 错误的请求格式 { name: "张三", // ❌ 缺少引号 'email': "test@example.com", // ❌ 单引号 age: "25" // ❌ 数字用了字符串 } // 正确的请求格式 { "name": "张三", // ✅ 双引号 "email": "test@example.com", // ✅ 双引号 "age": 25 // ✅ 数字类型 }
自动化测试
单元测试示例
实例
// 使用 Jest 测试框架
describe('用户 API 测试', () => {
test('应该能够获取用户列表', async () => {
const response = await fetch('/api/users');
const data = await response.json();
expect(response.status).toBe(200);
expect(data.success).toBe(true);
expect(Array.isArray(data.data)).toBe(true);
});
test('应该能够创建新用户', async () => {
const newUser = {
name: "测试用户",
email: "test@example.com"
};
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
});
const data = await response.json();
expect(response.status).toBe(201);
expect(data.success).toBe(true);
expect(data.data.name).toBe(newUser.name);
});
});
describe('用户 API 测试', () => {
test('应该能够获取用户列表', async () => {
const response = await fetch('/api/users');
const data = await response.json();
expect(response.status).toBe(200);
expect(data.success).toBe(true);
expect(Array.isArray(data.data)).toBe(true);
});
test('应该能够创建新用户', async () => {
const newUser = {
name: "测试用户",
email: "test@example.com"
};
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
});
const data = await response.json();
expect(response.status).toBe(201);
expect(data.success).toBe(true);
expect(data.data.name).toBe(newUser.name);
});
});
点我分享笔记