The mockJS implementation intercepts, emulating the XMLHttpRequest object. Rewrite the open, send, and other methods. When the method is called, it is just a normal function call, and does not send a real request.

MockJS use

  1. The introduction of mockjs
< script SRC = "https://cdn.bootcdn.net/ajax/libs/Mock.js/1.0.1-beta3/mock.js" > < / script >Copy the code
  1. Intercepts Ajax requests matching urls, generates mock data from the data template, and returns it as response data.
  Mock.mock('mock/news'.'GET', {
      'list|1-10': [{
          'id|+1': 1.'name': "@cname"}]})Copy the code
  1. Request url to get mock data
  axios.get('mock/news').then(res= > {
    console.log(res) // Res is simulated data in JSON format
  })
Copy the code

Ajax Interception Principles

  1. Override native XMLHttpRequest
  • The Ajax request creates an XMLHttpRequest object, overrides the native XMLHttpRequest, and when the Ajax request is made, it calls the function that we wrote

(source: / SRC /mock.js)

  MockXMLHttpRequest = require('./mock/xhr')
  Mock.mock = function(rurl, rtype, template) {...if (XHR) window.XMLHttpRequest = MockXMLHttpRequest
      ...
  }
Copy the code

As above, when the Mock. Mock method is called, window.XMLHttpRequest = MockXMLHttpRequest is executed to override the native XMLHttpRequest.

Now look at the MockXMLHttpRequest constructor

  1. Emulates native XMLHttpRequest

(source: /mock/ XHR /xhr.js)

  function MockXMLHttpRequest() {
      // Initialize the custom object to store custom properties
      this.custom = {
          events: {},
          requestHeaders: {},
          responseHeaders: {}
      }
  }
  Util.extend(MockXMLHttpRequest.prototype, {
      open: function(method, url, async, username, password) {
          var that = this
  
          Util.extend(this.custom, {
              method: method,
              url: url,
              async: typeof async= = ='boolean' ? async : true.username: username,
              password: password,
              options: {
                  url: url,
                  type: method
              }
          })
          ......
      },
      timeout: 0.withCredentials: false.upload: {},
      send: function send(data) {
          var that = this
          this.custom.options.body = data
          ......
          that.response = that.responseText = JSON.stringify(
              convert(that.custom.template, that.custom.options),// Generate JSON mock data from the data template
              null.4)},abort: function abort() {
          / / intercept XHR
          this.readyState = MockXMLHttpRequest.UNSENT
          this.dispatchEvent(new Event('abort'.false.false.this))
          this.dispatchEvent(new Event('error'.false.false.this))}})Copy the code

Open, send, abort and other functions, or attributes, are all common functions and attributes written by themselves.

The open function, for example, basically stores method and URL in variables. Send, which assigns the generated mock data to response and responseText

In this way, the response data is the simulated data set by the user.

When an Ajax request occurs, the request is not sent at all, just a few ordinary functions you write are called and the data is returned.