Mockjs的使用

  1. 引入mock
    yarn add mockjs -D
  2. 在项目根目录下新建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
}


  1. 在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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值