1. Premise basis

  • Based on the construction of VUE project and the configuration of VUe-Router route, this paper introduces the use of AXIOS in VUE project.

2. Use of Axios and setup of interceptors.

  1. Install axios
cnpm i axios -S
Copy the code
  1. Create HTTP folder, create index.js,config.js files
  2. Secondary encapsulation of AXIos is performed in config.js for request interception (mainly used to configure tokens and request data types) and response interception (mainly used for global processing of HTTP status codes and back-end custom codes).
  3. Import config.js in the index.js file and mount it on the vue prototype chain (or mount it on the vue instance object, skip it by reference on demand).
  4. Introduce the configuration in main.js as shown:
  5. Click the button to get the menu data. Here, express is used to start the service and encapsulate the menu API interface to simulate the real scene.
  6. Click the button, the effect is as shown in the picture.

3, API centralized management and on-demand reference.

  1. Centralized management of the API and on-demand references facilitate project management and refactoring, reducing the burden of vUE instances and optimizing project performance.
  2. We used to mount the wrapped AXIos directly to vue’s vue prototype chain and then use it in the component as this.$axios.get(), now we’ll modify it slightly.
  3. Delete require(‘./ HTTP ‘) from main.js, modify the index.js file under HTTP, and modify the interface references in home.vue. As shown in the figure:
  4. Now we go back to the page and see that it looks exactly the same.

4, summarize

  • The secondary encapsulation of AXIOS can unify the request/response data types of the front and back end interactions, unify the handling of HTTP error codes and custom codes, and avoid frequent judgments in components and confusing use of codes.
  • The centralized management and on-demand reference of THE API is conducive to project management and reconstruction, code reuse, the actual project development can be divided into modules of the API, the structure is clear.