Install axios

npm install axios -S
Copy the code

Create and use Axios

Normally we put the axios interceptor code in API /config

// Create a new axios const instance = axios.create({baseURL:'http://localhost:3000'}); // Make a request using instance({url:'/posts'}) instance.get()'/posts')

Copy the code

Normally we would just introduce Axios and just use it, but why do we need to create it now? The reason is as follows: axios create(config) a. Creates a new AXIos based on the specified configuration, that is, each new AXIos has its own configuration B. The new Axios just doesn’t have a way to cancel requests and batch them; everything else is a simple C. Why design this syntax?

Requirements: The configuration required by some interfaces in the project is different from that required by other interfaces. How to deal with thisCopy the code
Solution: Create two new Axios, each with its own unique configuration to apply to different variated interface requestsCopy the code

Interceptor for Axios

A basic case of error interception

import axios from 'axios';

export const baseUrl = 'http://localhost:3000'; Const axiosInstance = axios.create({baseURL: baseURL}); axiosInstance.interceptors.response.use( res => res.data, err => { console.log(err,"Network error"); });export {
  axiosInstance
};
Copy the code

One of the most basic token authentication interception

import Axios from 'axios'

Axios.interceptors.request.use(function (config) {
  let token = window.localStorage.token;
  if (token) {
    config.headers.Authorization = `token ${token}`}return config
}, function (error) {
  return Promise.reject(error);
});

Axios.interceptors.request.use(function (config) {
  return config
}, function(error) {// How to add rehops in react?return Promise.reject(error);
});
Copy the code

An Axios interception case in vUE

Jsvue.use (Vuex) vue.use (VueAxios, axios) vue.use (QS) In the request interceptor implementation axios. Interceptors. Request. Use (config = > {config. BaseURL ='/api/'
  config.withCredentials = trueConfig. timeout = 6000; // Allow the token to be carried, this is to solve cross-domain related problems config.timeout = 6000let token = sessionStorage.getItem('access_token')
  let csrf = store.getters.csrf
  if (token) {
   config.headers = {
    'access-token': token,
    'Content-Type': 'application/x-www-form-urlencoded'}}if (config.url === 'refresh') {
   config.headers = {
    'refresh-token': sessionStorage.getItem('refresh_token'),
    'Content-Type': 'application/x-www-form-urlencoded'}}return config
 },
 error => {
  returnPromise. Reject (error)}) / / in the response interceptor axios. Interceptors. Response. Use (response = > {/ / time to refresh the access tokenif(! response.data.value && response.data.data.message ==='token invalid') {// Refresh the token store.dispatch('refresh').then(response => {
    sessionStorage.setItem('access_token', response.data)
   }).catch(error => {
    throw new Error('token refresh' + error)
   })
  }
  return response
 },
 error => {
  return Promise.reject(error)
 }
)
Copy the code

In the above vUE interception example, request interception and response response interception are done. In fact, the interception code in VUE and React is the same. If you need to use it, you can directly use it.

After intercepting, AXIOS directly routes the jump

import Axios from 'axios'
import {HashRouter} from 'react-router-dom'

Axios.interceptors.request.use(function (config) {
  let token = window.localStorage.token;
  if (token) {
    config.headers.Authorization = `token ${token}`}return config
}, function (error) {
  return Promise.reject(error);
});

Axios.interceptors.request.use(function (config) {
  return config
}, function(error) {const router = new HashRouter() // Router.history.push ()'/')
  return Promise.reject(error);
});
Copy the code