- 引入mock
yarn add mockjs -D - 在项目根目录下新建mock/index.js
const Mock = require('mockjs')
// 接口配置
const mocks = [
{
url: "/user/content",
type: "get",
response: (config) => {
// 从config 获取请求参数,可依此对数据集合处理达到数据增删查改的目的
return Mock.mock({
"data|1-3": [
{
"id|+1": 1,
text: /title\d{1,3}/,
value: "提交的值1"
}]
})
}
},
{
url: "/user/submit",
type: "post",
response: (config) => {
return Mock.mock({
"data|1-3": [
{
"id|+1": 1,
text: /title\d{1,3}/,
value: "提交的值2"
}]
})
}
}
]
// 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
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
result = respond({
method: type,
body: JSON.parse(body),
query: param2Obj(url)
})
} else {
result = respond
}
return Mock.mock(result)
}
}
Mock.setup({
timeout: '200-600' //表示响应时间介于 200 和 600 毫秒之间。默认值是'10-100'。
})
for (const i of mocks) {
Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
}
}
module.exports = {
mockXHR
}
- 在main.js里注入mock
if(process.env.NODE_ENV === 'development') {
const {mockXHR} = require("../mock")
mockXHR();
}
此例中,我单独封装了request.js文件,做了proxy代理处理,在mock接口配置中不需要添加如"/api"等前缀
参考:
https://github.com/nuysoft/Mock/issues/300
http://mockjs.com/examples.html