答案
Whistle 提供了强大的数据模拟功能,可以在前端开发中模拟接口返回数据,提高开发效率。
数据模拟方法
1. 使用 resBody 操作符
直接指定模拟数据:
shellwww.example.com/api/user resBody://{"code":0,"data":{"name":"张三","age":25}}
2. 使用 Values 文件
创建 Values 文件存储模拟数据:
创建文件:mock-user.json
json{ "code": 0, "data": { "id": 1, "name": "张三", "age": 25, "email": "zhangsan@example.com" } }
配置规则:
shellwww.example.com/api/user resBody://{mock-user.json}
3. 使用 resScript 动态生成数据
创建脚本文件动态生成响应:
创建文件:mock-user.js
javascriptmodule.exports = function(req, res) { const userId = req.query.id || 1; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ code: 0, data: { id: userId, name: `用户${userId}`, timestamp: Date.now() } })); };
配置规则:
shellwww.example.com/api/user resScript://{mock-user.js}
4. 使用 whistle 插件
开发 whistle 插件实现更复杂的模拟逻辑:
javascriptmodule.exports = function(server, options) { server.on('request', function(req, res) { if (req.url === '/api/mock') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ mock: true })); } }); };
高级模拟技巧
1. 延迟响应
shellwww.example.com/api/* resScript://{delay-response.js}
delay-response.js:
javascriptmodule.exports = function(req, res) { setTimeout(() => { res.end(JSON.stringify({ code: 0, data: 'success' })); }, 2000); // 延迟2秒 };
2. 错误模拟
shellwww.example.com/api/error resBody://{"code":500,"message":"服务器错误"}
3. 条件模拟
根据请求参数返回不同数据:
javascriptmodule.exports = function(req, res) { const type = req.query.type; let data; if (type === 'success') { data = { code: 0, message: '成功' }; } else if (type === 'error') { data = { code: 500, message: '失败' }; } else { data = { code: 400, message: '参数错误' }; } res.end(JSON.stringify(data)); };
最佳实践
- 使用 Values 文件管理静态数据
- 使用 resScript 处理动态数据
- 按功能模块组织模拟数据
- 添加注释说明模拟数据的用途
- 定期清理不再使用的模拟规则