为什么要模拟服务器返回数据
为了不受接口开发进度影响,前端需要不依赖后台接口进行功能开发。我们只需要让后台提供接口文档,然后我们根据接口文档通过模拟数据返回完成功能开发。
例子
通过 获取紧急联系人列表
这个接口来看看如何实现模拟数据返回。
接口文档
请求参数:
序号 | 参数名 | 类型 | 必填 | 描述 |
---|---|---|---|---|
1 | usertoken | string | 是 | 用户token |
返回参数:
序号 | 参数名 | 类型 | 必填 | 描述 |
---|---|---|---|---|
1 | status | int | 是 | 0成功,其他值出错 |
2 | message | string | 否 | 描述信息 |
3 | ContactInfo | 是 | 紧急联系人列表 | |
3.1 | ID | string | 是 | id |
3.2 | ContactName | string | 是 | 联系人姓名 |
3.3 | ContactPhone | string | 是 | 联系人号码 |
返回示例
{
"ContactInfo": [{
"ID": 1,
"ContactName": "滴滴",
"ContactPhone": "13512345678"
},
{
"ID": 2,
"ContactName": "兔兔",
"ContactPhone": "12300000000"
},
{
"ID": 3,
"ContactName": "额额",
"ContactPhone": "54654644654"
}
],
"message": "请求成功,无异常",
"status": 0
}
通过 Fiddler 抓包修改返回内容
启动 Fiddler 并设置手机代理连接到本机,访问接口得到如下:

因为后台接口还没开发,所以请求错误,不过这对我们进行模拟数据返回没有影响。
以下介绍两种方式进行实现:
- 通过重定向到本地文件
- 通过重定向到 Easy Mock
通过指向本地文件模拟数据返回
- 根据接口提供的返回示例,编写返回内容的文件

- 通过指向本地文件返回正确数据

- 再次访问接口得到正确数据

使用 Easy Mock 模拟数据返回
-
打开 Easy Mock官网,进行注册登录
-
点击右下角新建项目(这个按钮是真难找,找了半天...)


- 创建接口

- 完成接口创建

- 通过 Fiddler 重定向刚创建的接口地址

网友评论