about

I was recently preparing to develop a Web application and decided to use MockJS as a Mock Server because of the possibility of parallel development on both the front and back ends.

Looking through the documentation on the official website, I found no examples of running on Webpack, so I had to find my own solution.

What is a mockjs? What are his usage scenarios?

When front-end engineers need to develop in parallel independently of the back-end, the back-end interface has not been completed, so how does the front-end get data?

Consider a front-end web server that simulates fake data itself and mockJs that generates random data to intercept Ajax requests.

Here’s a quote from mockJS:

Body: How to adapt Vue-CLI to embed MockJS in Webpack?

Vue project initialization

  1. Install vuE-CLI scaffolding tools and initialize the project
    // Global install vue-cli
    npm install vue-cli -g
    Create a new project based on the WebPack template
    vue init webpack mock-server-demo
    // Switch to the mock-server-demo directory
    cd mock-server-demo
Copy the code
  1. Install dependencies
    // We use AXIos to initiate HTTP requests
    npm install axios --save
    // Install the mockJS dependency
    npm install mockjs --save-dev
Copy the code

Build a Web server and respond to HTTP requests from the browser

Web Server does not need to build or install dependencies, it is already packaged in Webpack-dev-server, we just need to use it directly.

  1. Create a mock folder under the project root path and create several files in the mock folder in the image

  2. Index. Js file

    const Mock = require('mockjs');// Mockjs imports dependent modules
    const util = require('./util');// Customize the tool module
    // Return a function
    module.exports = function(app){
        // Listen for HTTP requests
        app.get('/user/userinfo'.function (rep, res) {
            // Read the mock Data json file every time you respond to a request
            The util. GetJsonFile method defines how to read json files and parse them into data objects
            var json = util.getJsonFile('./userInfo.json');
            // Pass json into the Mock. Mock method and the generated data is returned to the browser
            res.json(Mock.mock(json));
        });
    }
Copy the code
  1. Util. Js file
    const fs = require('fs');// Import the file system module
    const path = require('path');// Introduce the path module
    
    module.exports = {
        // Read the json file
        getJsonFile:function (filePath) {
            // Read the specified JSON file
            var json = fs.readFileSync(path.resolve(__dirname,filePath), 'utf-8');
            // Parse and return
            return JSON.parse(json); }};Copy the code
  1. The userInfo. Json file
    {
        "error":0."data": {"userid": "@id()".// Randomly generate user ids
            "username": "@cname()".// Randomly generate Chinese names
            "date": "@date()".// Randomly generate the date
            "avatar": "@image('200x200','red','#fff','avatar')".// Generate the image
            "description": "@paragraph()"./ / description
            "ip": "@ip()"./ / IP address
            "email": "@email()"//email}}Copy the code
  1. The path to build/webpack. Dev. Conf. DevServer attributes of js file new add a before hook function, used to monitor the HTTP request from the web. (How to use devServer.before)
    devServer: {
        clientLogLevel: 'warning'.historyApiFallback: {
          rewrites: [{from: /. * /.to: path.posix.join(config.dev.assetsPublicPath, 'index.html')},],},hot: true.contentBase: false.compress: true.host: HOST || config.dev.host,
        port: PORT || config.dev.port,
        open: config.dev.autoOpenBrowser,
        overlay: config.dev.errorOverlay
          ? { warnings: false.errors: true }
          : false.publicPath: config.dev.assetsPublicPath,
        proxy: config.dev.proxyTable,
        quiet: true.before: require('.. /mock'),/ / into a mock/index. Js
        watchOptions: {
          poll: config.dev.poll,
        }
      },
    
Copy the code

The browser issues a request to retrieve the mock data

  1. Use AXIos in the app.vue file to initiate HTTP requests
export default {
  name: 'App',
  data(){
    return {
      userInfo:{}
    }
  },
  created(){
    this.getUserInfo();
  },
  methods:{
    getUserInfo(){
     // Request the '/user/userinfo' interface
      this.axios.get('/user/userinfo')
      .then(({data}) = >{
        // Print mock data
        console.log(data);
        if(data.error === 0) {this.userInfo = data.data;
        }else{
          this.userInfo = {}; }}); }}}Copy the code

See the effect

You can see the randomly generated mock data that you get every time you click on the request.

The last

This page blog address is as a demo, more use methods can refer to the official code.

If the backend changes the agreed data structure, we have to start all over again. Mock Server is only a means to solve the problem to some extent.

Warehouse path


Original articles do not plagiarize!