# 使用本地Mock服务
# 开始使用
在项目目录新建cyb.config.mock.js
,填入以下示例内容:
//cyb.config.mock.js
const proxy = {
// 支持GET/POST
'GET /api/currentUser': {
name: 'furic-zhao',
userid: '00000001',
role: 'admin',
}
}
module.exports = proxy
执行cyb dev
或cyb test
,在开发或测试过程中访问http://localhost:8080/api/currentUser
会返回mock的数据。
# 高级使用
返回的数据支持对象、数组、以及函数、或者mockjs
等mock框架,几乎可以模拟任何的数据格式和数据环境。
- 支持数组
//cyb.config.mock.js
const proxy = {
'GET /api/users': [{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
}
]
}
module.exports = proxy
- 支持
mockjs
//cyb.config.mock.js
import mockjs from 'mockjs'
const proxy = {
'GET /api/tags': mockjs.mock({
'list|100': [{ name: '@city', 'value|1-100': 150, 'type|0-2': 1 }],
}),
}
module.exports = proxy
- 支持函数
//cyb.config.mock.js
const proxy = {
'POST /api/login/account': (req, res) => {
let postData = '';
req.on('data', function(chuck) {
postData += chuck;
})
req.on('end', function() {
const { userName, password, type } = JSON.parse(postData);
res.writeHead(200, { 'Content-Type': 'application/json' })
if (password === '888888' && userName === 'admin') {
res.end(JSON.stringify({
status: 'ok',
type,
currentAuthority: 'admin',
}));
return;
}
if (password === '123456' && userName === 'user') {
res.end(JSON.stringify({
status: 'ok',
type,
currentAuthority: 'user',
}));
return;
}
res.end(JSON.stringify({
status: 'error',
type,
currentAuthority: 'guest',
}));
})
}
}
module.exports = proxy
req
即http.ClientRequest
,res
即http.ServerResponse
,具体参考:nodejs的http模块。
为了平衡工具的复杂度,cyb-cli不支持MOCK数据热更新,仅用于项目与数据整合的演示,更完善的MOCK服务请使用塞伯坦CYBMOCK前端数据模拟服务器。