1. Introduction

In the front end of the development, will encounter and background interface tuning. Most of the time, the background and front-end development is parallel, front-end static interface function development, back-end interface business function development, this time, the background is unable to provide useful interface. In this case, a mock service is needed to provide simulated interface data for the front-end to debug, which will speed up front-end development and reduce the subsequent interfacing time with the middle and background.

The premise here is that the path of the interface and the structure of the return result and return fields need to be provided by the middle background. Mock services are only used in early development mode, and you can no longer rely on mock services if the middle background provides an interface to the development environment.

SPA front-end project is basically packaged by Webpack, using Webpack-dev-server for development and debugging. So you can use Webpack-dev-server to intercept the request by parsing the interface request path and returning the corresponding simulated interface data.

2. Devserver. before parses the request path and returns interface data

In the devServer option of WebPack, there is the hook method before, which performs custom functionality before all other middleware within the server. So, in this method, you get the path of the request, determine if it’s an interface request, and return the mock data for the interface.

The devServer configuration is as follows:

const {apiMocker} = require('.. /my-mock-server/index')

devServer: {
    headers: {
      "Access-Control-Allow-Origin": "*",},hot: true.host: '127.0.0.1'.port: '9000'.before: apiMocker
}
Copy the code

My-mock-server /index.js file contents:

const fs = require('fs')
const path = require('path')

const PREFIX = '/api/*'

function apiMocker(app, server) {
  app.get(PREFIX, handerAsyncRequest)
  app.post(PREFIX, handerAsyncRequest)
}

function handerAsyncRequest(req, res) {
  const reqPath = req.path.replace(/\/api/ig.' ')
  const filePath = path.resolve(__dirname, `./mocks${reqPath}.js`)
  if(! fs.existsSync(filePath)) { res.send('File does not exist')
    return
  }

  let data = require(filePath)
  res.send(data)
}

module.exports = {
  apiMocker
}
Copy the code

As shown above, devServer’s before method determines whether it is an interface request to read local mock data by parsing whether the request path contains the/API prefix. The data is stored locally under my-mock-server/mocks/*.

Once the local development environment service is started, such as http://127.0.0.1:9000, the mock server listens for the same address and port. In the interface call, you can make the call by setting baseURL to http://127.0.0.1:9000.

3. Scheme 2: Use Express to provide a mock server

In scenario 1, you can consider using mock data if it is essentially unchanged in use. Typically, mock data will be repeatedly modified to create a business scenario, and solution one will need to restart the service for the changes to take effect. So in order to provide hot update functionality for mock data, a second solution is to use Express to provide the service.

The Express service is still started using devServer.before, which starts the Express service within the hook method. The Webpack configuration is as follows:

devServer: {
    headers: {
      "Access-Control-Allow-Origin": "*",},hot: true.host: '127.0.0.1'.port: '9000'.before(app, server) {
      if (process.env.MOCK === 'true') {
        const entry = path.resolve(__dirname, '.. /my-mock-server/index.js')

        // the child_process module creates child processes
        require('child_process').exec(`node-dev ${entry}`)}}}Copy the code

My-mock-server /index.js file contents:

const fs = require('fs')
const path = require('path')
const cors = require('cors')
const express = require('express')

var app = express()
app.use(cors())

app.get('/api/demo1'.function (req, res) {
  const reqPath = req.path.replace(/\/api/ig.' ')
  const filePath = path.resolve(__dirname, `./mocks${reqPath}.js`)
  if(! fs.existsSync(filePath)) { res.send('File does not exist')
    return
  }

  let data = require(filePath)
  res.send(data)
})

var server = app.listen(9001.function () {
  var host = server.address().address
  var port = server.address().port

  console.log('Application instance, access at http://%s:%s', host, port)
})
Copy the code

After starting the development environment, Express listens on port 9001. The baseURL of the interface request in the business code needs to use http://127.0.0.1:9001. Express itself does not support hot updates, so node-dev is used to provide hot updates.

4. To summarize

The mock interface is a great aid to the implementation of front-end functionality during development and to the subsequent interplay with the backend development. The Example Here.