react-mock

数据mock
	1. 前期定义数据结构(后期不能改)
	2. 前期确定传参方式 resufApi (后期不能改)


	简洁:  会用,会改

		1. mock目录拷贝到项目下
		2. 修改package.json
			+ scripts 的 key
			"mock": "nodemon ./mock/server.js"
		3. yarn add json-server --save   安装依赖
		4. yarn add mockjs --save        安装依赖
		4.5 添加代理项
			  app.use(
			    proxy("/mock", {
			      target: 'http://localhost:3333',
			      changeOrigin: true
			    })
			  );

		5. yarn mock           启动mock服务器
		6. yarn start          启动react开发服务器

			组件内部发送请求:  /mock/接口名


		配置自己的数据接口:

			./mock/db.js

			'banner|2': [
		      {
		        // 属性 id 是一个自增数,起始值为 1,每次增 1
		        'id|+1': 1,
		        title: "@ctitle(4,8)",//标题型中文4到8个字
		        sub_title: "@ctitle(6,12)",
		        banner: mr.image('750x501', mr.color(), mr.cword(4,10)),//banner不变
		        time: "@integer(1553425967486,1553475967486)",
		        detail:{
		          icon:mr.image('20x20', mr.color(), mr.cword(1,2)),//20X20尺寸
		          auth:"@cname()",//百家姓
		          content:"@cparagraph(10,40)"//正文
		        }
		      }
		    ]

mock文件夹配置

npm i mockjs --save
npm json-erver --save
最后跑起来是npm run server
 
在pack.json 内更改


在mock内的db文件内

// 用mockjs模拟生成数据
var Mock = require('mockjs');

let mr = Mock.Random;//提取mock的随机对象

//随机id和图片
let mapData = (n) => {
  var data = [];

  for (var i = 1; i <= n; i++) {

    data.push({
      id: i,
      title: "@ctitle(8,12)",
      des: "@csentence(10, 20)",
      time: "@integer(1553425967486,1553475967486)",
      detail:{
        auth:"@cname()",
        content:"@cparagraph(10,40)",
        auth_icon:mr.image('50x50', mr.color(), mr.cword(1))
      }
    })
  }
  return data
};

//json-server 要对象||函数(返回mock后的数据)
module.exports = {
  ...Mock.mock({
    'home': mapData(32),//解决 auth_icon 不随机
    'follow': mapData(21),
    'column': mapData(11),
    'banner|2': [
      {
        // 属性 id 是一个自增数,起始值为 1,每次增 1
        'id|+1': 1,
        title: "@ctitle(4,8)",//标题型中文4到8个字
        sub_title: "@ctitle(6,12)",
        banner: mr.image('750x501', mr.color(), mr.cword(4,10)),//banner不变
        time: "@integer(1553425967486,1553475967486)",
        detail:{
          icon:mr.image('20x20', mr.color(), mr.cword(1,2)),//20X20尺寸
          auth:"@cname()",//百家姓
          content:"@cparagraph(10,40)"//正文
        }
      }
    ]
  })
};

在server.js文件内

const jsonServer = require('json-server');//在node里面使用json-server包
const db = require('./db.js');//引入mockjs配置模块

var Mock = require('mockjs');

let mr = Mock.Random;//提取mock的随机对象

const server = jsonServer.create();//创建jsonserver 服务对象
const router = jsonServer.router(db);//创建路由对象
const middlewares = jsonServer.defaults();

let mock='/mock';//创建根api名 这里的 /mock 如同 后端真实/api

//路由自定义
const rewriter = jsonServer.rewriter({
  [mock+"/*"]: "/$1",

  "/product\\?dataName=:dataName": "/:dataName",
  "/banner\\?dataName=:dataName": "/:dataName",
  "/detail\\?dataName=:dataName&id=:id": "/:dataName/:id",

  // "/product/del\\?dataName=:dataName&id=:id": "/:dataName/:id",
  // "/product/add\\?dataName=:dataName": "/:dataName",
  // "/product/check\\?dataName=:dataName&id=:id": "/:dataName/:id"
});

server.use(middlewares);

server.use((request, res, next) => {//可选 统一修改请求方式
  // console.log(1)
  // request.method = 'GET';
  next();
});

server.use(jsonServer.bodyParser);//抓取body数据使用json-server中间件

//模拟校验
server.use(mock+'/login', (req, res) => {
  console.log(req.query, req.body);//抓取提交过来的query和body
  let username=req.query.username;
  let password=req.query.password;
  (username === 'aa' && password === 'aa123')?
    res.jsonp({
      "error": 0,
      "msg": "登录成功",
      "page_data": {
        "follow": mr.integer(1,5),
        "fans": mr.integer(1,5),
        "nikename": mr.cname(),
        "icon": mr.image('20x20',mr.color(),mr.cword(1)),
        "time": mr.integer(13,13)
      }
    }) :
    res.jsonp({
      "error": 1,
      "msg": "登录失败",
    })

});
server.use(mock+'/reg', (req, res) => {
  let username=req.query.username;
  (username !== 'aa') ?
    res.jsonp({
      "error": 0,
      "msg": "注册成功",
      "page_data": {
        "follow": mr.integer(0,0),
        "fans": mr.integer(0,0),
        "nikename": mr.cname(),
        "icon": mr.image('20x20',mr.color(),mr.cword(1)),
        "time": mr.integer(13,13)
      }
    }) :
    res.jsonp({
      "error": 1,
      "msg": "注册失败",
    })

});

server.use(rewriter);//路由重写
server.use(router);//路由响应

//自定义返回内容
router.render = (req, res) => {
  let len = Object.keys(res.locals.data).length; //判断数据是不是空数组和空对象
  // console.log(len);

  setTimeout(()=>{
    res.jsonp({
      error: len !== 0 ? 0 : 1,
      msg: len !== 0 ? '成功' : '失败',
      page_data: res.locals.data
    })
  },1000)

  // res.jsonp(res.locals.data)

};


//开启jsonserver服务
server.listen(3333, () => {
  console.log('mock server is running')
});

最后再把react跑起来 npm start

import React from 'react'
import ReactDom from 'react-dom'

class App extends React.Component{

  state={
    msg:'-',
  };

  render(){

    return (
      <div className="app">
        <h3>mock</h3>
        <input type="button" value="读接口_地址栏传参" onClick={this.getMock}/>
        <input type="button" value="读接口_非地址栏传参" onClick={this.postMock}/>
        <input type="file" ref="f1" />
        <input type="button" value="读接口_上传文件" onClick={this.postMockFile}/>
      </div>
    )

  }


  getMock = () => {
    fetch(
      `/mock/home?_page=2&_limit=2`
    ).then(
      res => res.json()
    ).then(
      data => console.log(data)
    )
  };
  postMock = () => {

    let params = new URLSearchParams();
    params.append("username","alex");
    params.append("password","alex123");


    let headers = new Headers();
    headers.append("Content-type","application/x-www-form-urlencoded");


    fetch(
      `/mock/login`,
      {
        method:'POST',  //默认get
        // headers:{"Content-type":"application/x-www-form-urlencoded"},
        headers:headers,
        // body:params//{username:'alex',password:'alex123'}//URLSearchPrams
        body:"username=alex&password=alex123"
      }
    ).then(
      res => res.json()
    ).then(
      data => console.log(data)
    )

  };

  postMockFile = () => {
    let formData = new FormData();

    formData.append("username", "heheda");
    formData.append("password", "heheda123");
    formData.append("nikename", "2019-7-10");

    // HTML 文件类型input,由用户选择
    formData.append("icon", this.refs.f1.files[0]);

    fetch(
      `/mock/reg`,
      {
        method:'POST',  //默认get
        // body:params//{username:'alex',password:'alex123'}//URLSearchPrams
        body:formData
      }
    ).then(
      res => res.json()
    ).then(
      data => console.log(data)
    )

  }

}

ReactDom.render(
  <App/>,
  document.querySelector('#app')
);
posted @ 2019-07-11 09:56  进击的三三  阅读(2575)  评论(0编辑  收藏  举报