mockjs拦截请求,生成假数据

在前后端分离的时代,前端开发不再过渡依赖于后端。在接口未开发的情况下,前端可以依据约定好的接口进行开发,借助mockjs拦截请求,制造假数据进行响应。

1、mockjs安装

npm install mockjs

2、mockjs配置

mockjs语法规范详见:https://github.com/nuysoft/Mock/wiki/Syntax-Specification

1)mock文件配置(mock/index.js)

const Mock = require('mockjs')
// 接口配置
const mocks = [
  {
    url: "/api/flow",
    type: "get",
    response: config => {
      return Mock.mock({
          "data|1-3": [
          {
            "id|+1": 1,
            text: /title\d{1,3}/,
            value: "提交的值"
          }]
        })
      }
  },
  {
    url: "/api/flow/submit",
    type: "post",
    response: config => {
      return Mock.mock({
        "data|1-3": [
        {
          "id|+1": 1,
          text: /title\d{1,3}/,
          value: "提交的值"
        }]
      })
    }
  }
]

/**
 * @param {string} url
 * @returns {Object}
 */
function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

// 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
        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
}

2)mockjs调用

在启动项目的js文件(main.js)中加入如下代码:

const { mockXHR } = require("../mock");
mockXHR();

以上步骤操作完,即可捕获mockjs配置文件中已配置的接口请求,并响应配置好的数据。

你可能感兴趣的:(mockjs,前端,mockjs拦截请求,mockjs制造假数据)