Before, when developing the background management system, I developed it with other colleagues. To be honest, I wrote pages on the basis of others' development...
Now I want to pick up the points I didn't pay attention to before..
Today, let's look at the usage of axios interceptor
When writing code with vue, axios can be used to make ajax requests. Specifically, it is equivalent to verifying (intercepting) before the request and verifying (intercepting) before the response
What is axios
axios is an HTTP client based on Promise for browsers and nodejs. The simple understanding is ajax encapsulation
It has the following characteristics:
- . create XMLHttpRequest from the browser
- From node JS issue http request
- Promise API supported
- Intercept requests and responses
- Transform request and response data
- Cancel request
- Automatically convert JSON data
- Client support prevents CSRF/XSRF
axios official website address: https://www.npmjs.com/package/axios
npm installation method:
$ npm install axios
axios usage
1. Create a js file in the src directory and import axios
import axios from 'axios'; //Introducing axios //The following two do not have to be introduced. It depends on what the project needs to do during interception. Generally, the store needs to be introduced because the user's login information can be obtained import store from '@/store/index';//Introducing store import router from '@/router';//Introducing router
2. Create an axios instance
let instance = axios.create({ headers:{ 'content-type':'application/x-www-form-urlencoded' } })
3. Write a request interceptor
The interceptor will run before you send the request. The function of the request interceptor here is to judge whether there is a token before each request. If a token exists, add the token to the request header, and the background will judge whether the token has expired.
// http request interceptor instance.interceptors.request.use( config=>{ const token = localStorage.getItem('token');//You can also use this localStorage or store here, because the login information is usually stored in vuex after login, but if it is not stored in localsStorage, the content in vuex will disappear when the current page is refreshed. if(token){ config.headers.authorization = token //Request header plus token } return config },err=>{ return Promise.reject(err); } )
4. Write a response interceptor
The interceptor will respond after getting the data returned by the background interface. For example, the correct return code of the data is 200. If the code is 500, it needs to be intercepted.
instance.interceptors.response.use( response = { //Intercept the response for unified processing if(response.data.code){ switch(response.data.code){ case 1002: store.state.isLogin = false;//An isLogin in the store indicates the login status, which depends on the specific situation router.replace({ path:'login', query:{ redirect:router.currentRoute.fullPath } }) } } return response }, //Interface error status processing, that is, processing when there is no response error =>{ return Promise.reject(error.response.status);//Error message returned by interface } )
5. Export instance
export default instance
6. Use of Axios
In the js file corresponding to the interface, use axios, such as login js login related interface
import axios from './axios' /* Verify login */ export function handleLogin(data){ return axios.post('/user/login',data) }
On the login page, you can directly import login JS, and then use handleLogin.
<script> import loginApi from '@/api/login.js' export default{ data(){}, created(){ loginApi({xxx}).then(res=>{ console.log(res); }).catch(err=>{ console.log(err); }) } } </script>
The following appendix is a code of great God when I first worked on vue front-end:
import axios from 'axios'; import router from '@/router/routers'; import {Notification,MessageBox,Loading} from 'element-ui'; import store from '../store' import {getToken} from '@/utils/auth' import Config from '@/setting' var qs = require('qs')//qs is mainly used to process the data of formData //Create an axios instance const service = axios.create({ baseURL:process.env.NODE_ENV ==='production'?process.env.VUE_APP_BASE_API:'/',//api base_url timeout:Config.timeout //Request time }) let loadingInstance //request interceptor service.interceptors.request.use( config=>{ if(getToken()){ config.headers['Authorization'] = getToken() //Let each request carry a custom token. Please modify it according to the actual situation } config.headers['Content-Type'] = 'application/json' //The content type of this header header is generally application/json, but some interfaces need to pass in formData format. In this case, qs is required. In order to distinguish, add a type variable to the config parameter for judgment if(config.type && config.type == 'form'){ config.headers['Content-Type'] = 'application/x-www-form-urlencoded' if(config.data){ config.data = qs.stringify(config.data); } } if(config.loading){ loadingInstance = Loading.service({fullscreen:true}) } return config }, error =>{ console.log(error); Promise.reject(error); } ) //response interceptor service.interceptors.response.use( response =>{ const code = response.status if(code<200 ||code>300){ Notification.error({ title:response.message }) if(loadingInstance){ loadingInstance.close(); } return Promise.reject('error') }else{ if(loadingInstance){ loadingInstance.close(); } return response.data } }, error =>{ let code = 0 try{ code = error.response.data.status }catch(e){ if(error.toString().indexOf('Error:timeout') !==-1){ Notification.error({ title:"Network request timeout", duration:5000 }) return Promise.reject(error) } } if(code){ if(code==401){ MessageBox.confirm( 'The login status has expired. You can stay on this page or log in again', 'System prompt', { confirmButtonText:'Login again', cancelButtonText:'cancel', type:'warning' } ).then(()=>{ store.dispatch('Login').then(()=>{ location.reload();//To re instantiate the Vue router object }) }) }else if(code==405){ router.push({path:'/401'}) }else{ const errorMsg = error.response.data.message if(errorMsg !== undefined){ Notification.error({ title:errorMsg, duration:5000 }) } } }else{ Notification.error({ title:'Interface request failed', duration:5000 }) } return Promise.reject(error) } ) export default service
Contents of interface documents:
import request from '@/utils/request' //get request is written as follows: export function getShopList(data, loading) { // eslint-disable-next-line no-return-assign return get('api/shop/list', data, loading) } //How to write a post request: export function modifyAdmin(data) { return request({ url: 'api/shop/modify/admin', method: 'post', data }) } //How to write a post request in formData format: export function verify(data) { return request({ type: 'form', url: 'api/shop/verify', method: 'post', data }) }
Some contents of interfaces used in vue page:
import { verify } from '@/api/shop' ... methods:{ verify(this.verifyObj).then(res => { .... }).catch(error => { ... }) }