react mockjs mock 数据,让前端不在等待后端接口

2019-07-29  本文已影响0人  日不落000
  mockable: true,
import mock from 'appRoot/mock';
      if (res && res.ok && res.statusCode === 200) {
        const text = res.body || JSON.parse(res.text);
        promise = Object.assign({}, text);
        return promise;
      }

src/mock/index.js

import { config, } from 'appRoot/utils';
const all = config.mockable ? require('./all'): null;

src/mock/all.js


// 将所有的mock文件引入
import tmp from './tmp';

// 在这里可以做一些通用的配置

import Mock from 'mockjs'

Mock.XHR.prototype.__send = Mock.XHR.prototype.send
Mock.XHR.prototype.send = function () {
  if (this.custom.xhr)
    this.custom.xhr.withCredentials = this.withCredentials || false
  this.__send.apply(this, arguments)
}

// 设置所有ajax请求的超时时间,模拟网络传输耗时
Mock.setup({
    timeout: 0-300
})

以后在类似tmp.js 文件中添加mock返回;

src/mock/tmp.js

import Mock from 'mockjs'
import { config, } from 'appRoot/utils';
Mock.mock(`${config.rootApi}/tmp`, "get", function(){
  let data = Mock.mock({
        "code": 0,
        "data": {
          "fullName": "@CNAME", // 随机生成中文人名
          "userId": 1000234234001,
          "username": "zhangsan"
        },
        "msg": "success"
    });
  return data;
});
上一篇下一篇

猜你喜欢

热点阅读