Several ways to use Mock data in the project

Several ways to use Mock data in the project

  • Demand background : In a large environment with separate front-end and back-end, the front-end needs to obtain the data of the back-end interface to render the page. In this case, when the back-end development progress is behind schedule, the front-end development is also hindered. Therefore, the front end needs static simulation data for debugging.

  • Mock data (simulation data) generation method :       

       Create manually. However, the problem with this method is also obvious, especially when the data content is more complex or when the data volume is large, creating mock data is very time-consuming.

       Use mockjs. Mockjs can generate mock data according to the data template. Many developers now use mockjs to generate mock data. The method described in this article is also based on mockjs.

       Use a third-party online mock platform. For example: Easy Mock

  • Mock data combat

        1. Install npm install mockjs

        2. Create a new mock folder in the project directory, and put the contents related to the mock data here.

    3. Build mock data

//mock/data/index.js
const Mock = require("mockjs");
module.exports = [
  Mock.mock("/mock/getData", {
    "data|10": [
      {
        "key|+1": 1,
        "words|1": ["哈哈", "嘿嘿", "biubiu", "啾啾", "喵喵","啦啦"],
        "activity|1": ["吃饭", "睡觉", "打豆豆"]
      }
    ]
  })
];

    4. Turn on the mock data service:

        method one:

               Import mock data files in the entry file and request mock data

import React,{Component} from "react";
import axios from "axios";
import '../mock/data/index';

class App extends Component {
    constructor(props) {
    	super(props);
    	this.state = {
      		mockData: ""
    	};
  	}
    componentDidMount(){
        axios.get("/mock/getData").then(res => {
      		console.log("This is mock data : ", res.data);
             this.setState({
        		mockData: res.data
     		});
    	});
    }
    render() {
        return (
        	<div>
            <h2>mock数据:</h2>
            <div>{this.state.mockData}</div>
            </div>
        )
    }
}

At this time, the output of mock data can be seen on the console and the page. However, this method of use needs to be referenced in every file that uses mock data. If you do not use mock data after joint debugging, you also need to manually comment.

There are two other points to note:

1. Mock data requested in this way is not captured in the browser's Network because it is a fake ajax
2. It is impossible to request data when sending ajax with fetch. Mockjs may not support fetch at present.

            Method 2: Configure the package.json file of the project and start the mock service through node.

            Create mockServer.js file

//mock/server/mockServer.js
let express = require("express"); //引入express
let Mock = require("mockjs"); //引入mock
let app = express(); //实例化express
//设置允许跨域
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  next();
});

app.get("/mock/getData", function(req, res) {
  res.json(
    Mock.mock({
    "data|10": [
      {
        "key|+1": 1,
        "words|1": ["哈哈", "嘿嘿", "biubiu", "啾啾", "喵喵","啦啦"],
        "activity|1": ["吃饭", "睡觉", "打豆豆"]
      }
    ]
  })
});
app.listen("4000", () => {
  console.log("监听端口 4000");
});

            Modify the package.json configuration, and then only need to npm run mock after the project runs.

//package.json部分代码
"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start && npm run mock",
    "type-check": "tsc",
    "pm2:start": "npm run build && pm2 startOrRestart ecosystem.config.js --env production",
    "pm2:stop": "pm2 stop linkchain",
    "pm2:deploy": "pm2 deploy ecosystem.config.js dev",
    "mock": "node ./mock/server/mockServer"//开启mock服务
  }

Requesting mock data in this way can capture the request information in the browser's Network.

However, this method also has a shortcoming: hot loading cannot be achieved. Each time the mock data-related files are modified, the current mock service must be killed and the mock service restarted again to take effect, which will also add some trouble to development.

Of course, there are definitely other better ways to use mock data in the project, and I will update it after I learn!

Published 50 original articles · Likes5 · Visits 20,000+

Guess you like

Origin blog.csdn.net/qq_31207499/article/details/102585938