1. Global configuration of axios
1. Why global configuration of axios
In actual project development, almost every component will be used axios initiates a data request. At this time, you will encounter the following two problems:
① Each component needs to import axios (bloated code)
② Every time you send a request, you need to fill in the complete request path (not conducive to Later maintenance) [Related recommendations: vue.js video tutorial]
2. How Global configuration axios
In the main.js entry file, mount axios globally through app.config.globalProperties. The sample code is as follows:
3. Global configuration of axios in the vue2 project
Needs to configure axios globally through the prototype prototype object of the Vue constructor in the main.js entry file
2. axios interceptor
Interceptors (English: Interceptors) will be automatically triggered every time an ajax request is made and a response is received.
2. Configure request interceptor
Pass axios.interceptors.request.use(successful callback, failure callback) Request interceptors can be configured. The sample code is as follows:
2. Solve cross-domain problems of interfaces through proxies
When projects created through vue-cli encounter cross-domain problems with interfaces, they can be solved through proxies:
① Set the request root path of axios to the running address of the vue project (interface requests no longer cross domain)
② vue The project finds that the requested interface does not exist, and forwards the request to the proxy agent
③ The proxy replaces the request root path with the value of the devServer.proxy attribute and initiates a real data request
④ The proxy forwards the request The received data is forwarded to axios
3. Configure proxy in the project
Step 1. In the main.js entry file, change the request root path of axios to the current web project Root path:
Step 2, create the vue.config.js configuration file in the project root directory , and declare the following configuration: