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.
- Install axios
cnpm i axios -S
Copy the code
- Create HTTP folder, create index.js,config.js files
- 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).
- 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).
- Introduce the configuration in main.js as shown:
- 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.
- Click the button, the effect is as shown in the picture.
3, API centralized management and on-demand reference.
- Centralized management of the API and on-demand references facilitate project management and refactoring, reducing the burden of vUE instances and optimizing project performance.
- 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.
- 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:
- 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.