在日常项目中,由于前后端分离后端又没有及时提供接口,因此经常需要前端自己mock数据。下面主要介绍使用charles这个软件进行mock数据的方法
1. 首先当然是下载charles这个软件:https://www.charlesproxy.com/latest-release/download.do 根据自己系统下载对应的包,安装一直点下一步即可。
2.接下来在桌面或者其他地方新建一个json文件,里面写上你需要mock的数据。
3.打开刚才安装的charles软件:

4.然后在charles中配置tools -> Map Local Settings:

5.点击add按钮后在弹窗中填入协议、域名、端口、请求路径和要mock的文件路径。填完之后点击OK

填写完相关信息后这里就会多出一条刚刚填的信息勾选它, Enable Map Local也要勾选。最后点击OK就完成了所有配置。

6. 在你的代码中调用下刚刚填写的请求路径,运行代码在浏览器控制台看看是否请求成功。

按照上面步骤配置好后还是报错404的解决方法:
如果还是报错404,你需要重新配置第五步,tools -> Map Local Settings 双击刚刚添加的哪条信息。然后host这一栏改成http://localhost.charlesproxy.com/ 其他不用动:

最后浏览器中访问时不能直接使用localhost加端口号,要用localhost.charlesproxy.com加端口号,如:http://localhost.charlesproxy.com:3000/ 。这样就不会报404请求也成功啦!

网友评论