Front-end separate development uses mock.js

Front-end and back-end separate development is the mainstream of the current industry. A previous blog once mentioned this problem. At that time, I recommended using yapi to simulate data.
Then using yapi requires cost, whether the company has a yapi account, the cost of opening a yapi account, the data simulated by yapi is not in the front-end project, and so on.

You can install mock.js, export the configured interfaces and data, and import them at the top of the project. When sending an Ajax request, you can intercept the request and return the mock data.

installation

npm install mockjs --save
或
yarn add mockjs

Create a mock folder in the src directory, and create a mock.js folder

import Mock from "mockjs";

// eslint-disable-next-line
Mock.mock('http://test123.com', {
    
    //这里的url地址其实可以换成一个字段,比如msg,下边请求时候对应就可以
  'name': '@cname',
  'age|1-10': 10
})
Mock.mock('http://myname.com','post', {
    
    //这里的url地址其实可以换成一个字段,比如msg,下边请求时候对应就可以
  'data|1-2':[{
    
    
    'title':'@title',
    'article':'@csentence'
    }]
})

Introduce the created mock.js at the top level of the project

Take the react project as an example, the top level of the project is index.js
Insert picture description here

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
// 导入mock.js文件
import './mock/mock'
import './index.less';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Request an interface in a component or page

axios.get("http://test123.com").then((res) => {
    
    
      console.log(res);
      //结果是随机的,也有可能是其他值
    });

It was found that this interface was not requested
Insert picture description here
because the request was intercepted by mock.js, but the data we wanted was returned
Insert picture description here

mockjs official website: http://mockjs.com/

You can return different random data through different writing methods

Guess you like

Origin blog.csdn.net/glorydx/article/details/114491171