Basic axios usage
1. Download axios
yarn add axios -S
npm i axios -S
2. Encapsulate request tools
- SRC create utils/request.js
import axios from 'axios' const request = axios.create({ baseURL: Export default ({method = 'GET', URL, params, data, headers}) => {return request({method, URL, headers}) params, data, headers }) }
After library change, only need to change here, the logical page is not moved, to ensure code reuse and independence (high cohesion and low coupling)
3. Encapsulate the interface tool
- SRC create API/various interface function files
Import $customFn from '@/utils/request.js' const customFn = (data, params, headers) => {return $HTTP ({method: 'Default: GET', URL:' request address ', data, Params,headers,// receive on demand})} export {customFn} // Export on demand
4. Project application
- Import interface function files as required
- The function is called to send the request
Import {customFn} from '@/ API/API 'async function Fn(data, params, Try {const {data:res} = await customFn(data, params, } catch(error) {console.log(error)}}
Async and await can only receive the return value of the success status. Together with try-catch, they can receive the return value of the failure status
Axios interceptor
1. Request an interceptor
/ / add request interceptor axios. Interceptors. Request. Use (function () {return} config / / send the request of the data, Function (error) {// do something about the request error return promise.reject (error)})
2. Respond to the interceptor
/ / add the response interceptor axios. Interceptors. Response. Use (function (response) {/ / when a status code of 2/3 xx xx opening here / / to do something about the response data return response}, Function (error) {return promise.reject (error)})
3. Remove the interceptor
const myInterceptors = axios.interceptors.response.use(...)
axios.interceptors.response.eject(myInterceptors)