在前端开发过程当中,若是后端接口尚未提供,前端拿不到数据一些交互行为的代码可能就无法继续写,这时咱们一般本身造一些数据来让页面流程走下去,最近项目切换到vue框架开发,发现json-server能很好的解决接口mock的问题javascript
$ npm install json-server -g
vue
启动json-server$ json-server --watch db.json
java
经过官方的例子你能够发现json-server
实际上是在你访问接口时,返回db.json
里面的对应的key
的值
例如:你访问 http://localhost:3000/posts/
返回db.json
里面的json.posts
git
那么问题来了
1.若是咱们要模拟的接口很是多,要一个一个的往db.json
里面添加吗,其余前端人员也会修改到这个文件,每次合并代码都要考虑冲突问题,并且这个文件会变得很是庞大,难以维护
2.若是个人接口是http://localhost:3000/a/b
,http://localhost:3000/a/b/c
怎么解决github
本文就主要探讨下这两个问题的解决方案:npm
1,修改package.json
里面的npm run mock
对应的命令为 json-server mock/index.js
在项目中创建mock文件夹,文件夹下创建index.js
(名字随意)文件,
index.jsjson
module.exports = function () { return { a: ['接口a的返回数据'], b: ['接口b的返回数据'] } }
此时启动npm run mock
,访问http://localhost:3000/a
,能够得到想要的结果
2,在mock文件夹下新建几个js文件,例如我新建了后端
└─ mock │─ test │ ├─ a.js │ └─ b.js └─ test2 ├─ c.js └─ d.js
举例其中一个a.jsapi
module.exports = { url: 'a', title: '', type: 'GET', decs: '', query: { a: '1' }, res: { ret: 1, result: [ { a: '2', b: '3', c: '4' } ] } }
修改index.js
let Path = require('path') let glob = require('glob') // 读取全部API文件 const apiFiles = glob.sync(Path.resolve(__dirname, './') + '/**/*.js', { nodir: true }) let data = {} // 输出全部api文件 i从1开始 跳过index.js for (let i = 1, l = apiFiles.length; i < l; i++) { let api = require(apiFiles[i]) if (api.url) { data[api.url] = api.res } } module.exports = function () { return data }
而后启动mock,你会看到控制台打印
Resources http://localhost:8083/a http://localhost:8083/b http://localhost:8083/c http://localhost:8083/d
成功的实现了每一个api分离,添加一个api咱们只须要复制一个js文件,删除和修改也只是改动咱们本身的文件,不会影响到团队其余成员
a/b
,a/b/c
怎么办修改index.js
let Path = require('path') let glob = require('glob') const apiFiles = glob.sync(Path.resolve(__dirname, './') + '/**/*.js', { nodir: true }) let data = {} for (let i = 1, l = apiFiles.length; i < l; i++) { let api = require(apiFiles[i]) if (api.url) { data[api.url.replace(/\//g, '_')] = api.res } } module.exports = function () { return data }
启动mock服务,咱们会看到
Resources http://localhost:8083/a http://localhost:8083/a_b http://localhost:8083/a_b_c http://localhost:8083/a_b_c_d
而后在项目根目录下添加json-server.json
文件
{ "port": "8888", "routes": "./mock/routes.json" }
在mock文件夹下添加routes.json文件
{ "/*/*/*/*/*": "/$1_$2_$3_$4_$5", "/*/*/*/*": "/$1_$2_$3_$4", "/*/*/*": "/$1_$2_$3", "/*/*": "/$1_$2" }
这样咱们就将每次请求的路径相似 a/b/c/d/e
转换成了a_b_c_d_e
启动mock服务,而后访问路径localhost:8888/a/b/c/d/e
,完美
最后贴一下本文中所用到的文件的目录结构
└─ mock │ │─ test # 文件夹1 │ │ ├─ a.js # api1 | │ └─ b.js # api2 | ├─ test2 # 文件夹2 | │ ├─ c.js # api3 | │ └─ d.js # api4 | ├─ index.js # 出口文件 | └─ routers.json # 路径转换配置文件 ├─ json-server.json # 端口等配置 └─ package.json # 项目配置
本文系做者搭建mock服务的一点心得,若有关于搭建mock服务的优雅的解决方案,欢迎各路大神与做者沟通交流,欢迎指正本文中的错误