对于axios的封装

 1 import axios from 'axios'
 2 import axiosRetry from 'axios-retry'; //网络不佳,重新发起请求
 3 import { getToken, removeToken, getAuthorization} from '@/utils/auth'
 4 
 5 axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
 7 
 8 // 创建axios实例
 9 const service = axios.create({
10   // axios中请求配置有baseURL选项,表示请求URL公共部分
11   baseURL: process.env.VUE_APP_BASE_API,
12   // 超时
13   timeout: 0
14 })
15 
16 axiosRetry(service, {
17   retries: 3 //网络不佳的请求次数
18 });
19 
20 // request拦截器
21 service.interceptors.request.use(config => {
22   if (getToken()) {
23     config.headers['Access-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
24   }
25 
26   if (getAuthorization()) {
27     config.headers['Authorization'] = 'Bearer '+ getAuthorization()
28   }
29   return config
30 }, error => {
31     console.log(error)
32     Promise.reject(error)
33 })
34 
35 // 响应拦截器
36 service.interceptors.response.use(res => {
37     if (res.status === 401) {
38       //如果无用户权限,做跳转处理
39       removeToken();
40       location.href = '/webapp/my/login';
41     } else if (res.status !== 200) {
42       //非 200 统一做异常处理
43       
44     } else {
45       //200 返回正确数据
46       return res.data
47     }
48 
49   },
50   error => {
51     if (error.response.status === 401) {
52       //如果无用户权限,做跳转处理
53       removeToken();
54       location.href = '/webapp/my/login';
55     }
56     return Promise.reject(error)
57   }
58 )
59 
60 export default service



///引入请求
import request from '@/utils/request'
export function fukName(data) {
  return request({
    url: '',
    method: 'post',
    data: data
  })
}
原文地址:https://www.cnblogs.com/crazy-rock/p/15088473.html