Tool module encapsulation

Encapsulate the AXIOS module

background

Repetitive work is abstracted and encapsulated into modules for easy code maintenance and reuseCopy the code

The main points of

  • 1. Url and API encapsulation
  • Request and Response interceptors
  • 3. Axios is packaged as a Vue plug-in

File structure

SRC create a new HTTP folder and store the HTTP and API interaction code. The structure is as follows: config.js: axios default configuration, basic path information, etc. Axios: encapsulates the AXIos module containing request and response interception and request processing api.js: All requests are summarized by modules, and all modules are aggregated by API index.js: Module: the user divided the module into API SRC and then created utils file to store the general JS file global.js: store the common global configuration, constants and methods, and call eg through this.global: Later server address, background backup server address main.js 1. Import the API module and register with vue.use (API), which is available via the "this.$API. Submodule. Method "to call the background interface. Var prototype.global = global; var prototype.global = globalCopy the code

Js – cooklie installation

In axios.js, we use cookies to fetch tokens, so we need to download the dependencies,

test

Note:

  • 1. Before using plug-ins, you must introduce plug-ins into the plugin to use it
  • 2. Mock the interface with the same port number as baseUrk in the global.js file

Personal understanding of some code

  • 1. Arrow function
  • Param =>{}; param =>{}; param =>{}; param =>{}; Such asMock.mock(new RegExp(url),res.type,(opts) =>{ opts['data'] = opts.body? JSON.parse(opts.body):null delete opts.body console.log('\n'); Console. log('%cmock intercepts, request: ','color:blue',opts); Console. log('%cmock intercept, response: ','color:blue',res.data); return res.data })Opts is a parameter, assuming the body attribute exists, as long as the input parameter is included when the function is called later