在前后端分离开发的过程中,一般都是协同同步开发,即这个时候并不能立马和后端进行联调,但是又为了不耽误前端进度,推进前端业务逻辑,推荐使用mock模拟报文数据
步骤如下:
1.npm 下载mock
这个就没啥可说的了
2.main.js进行配置
if (process.env.NODE_ENV === 'development') {
const { mockXHR } = require('../mock')
mockXHR()
}
代表只在开发模式下,使用mock,生产模式下,将关闭mock,连接真正的后台
3.mock.js处理拦截的url
const Mock = require('mockjs')
const { param2Obj } = require('./utils')
const admin = require('./admin/')
const mocks = [
...admin,
]
// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
function mockXHR() {
// mock patch
// https://github.com/nuysoft/Mock/issues/300
Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
Mock.XHR.prototype.send = function() {
if (this.custom.xhr) {
this.custom.xhr.withCredentials = this.withCredentials || false
if (this.responseType) {
this.custom.xhr.responseType = this.responseType
}
}
this.proxy_send(...arguments)
}
function XHR2ExpressReqWrap(respond) {
return function(options) {
let result = null
if (respond instanceof Function) {
const { body, type, url } = options
// https://expressjs.com/en/4x/api.html#req
result = respond({
method: type,
body: JSON.parse(body),
query: param2Obj(url)
})
} else {
result = respond
}
return Mock.mock(result)
}
}
for (const i of mocks) {
Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
}
}
module.exports = {
mocks,
mockXHR
}
4.api接口以及mock模拟的接口
export function login(loginBody) {
return request({
url: '/login',
method: 'post',
data: loginBody
})
}
// 登录
{
url: '/login',
type: 'post',
response: adminInit,
},
{
"errorMessage": "",
"errorCode": "",
"data": {
"user": {
"account": "superAdmin",
"role": "SuperAdmin"
}
}
}
注意:url、type方式一定要和真正的接口匹配上,否则拦截不到,adminInit是模拟的请求报文
以上只是简单的步骤,由于涉及到代码比较多,只贴出了一部分,有需要完整的可以私信找我拿哈~