vue axios 封装(二)

封装二:

http.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import axios from 'axios'
import storeHelper from './localstorageHelper'
// 全局设置
const obj = storeHelper.getStorageObject()
if (obj && obj.tokenInfo) {
  // console.info("http.js", obj);
  axios.defaults.headers.common['Authorization'] = 'bearer ' + obj.tokenInfo.access_token
}
const apiRoot = process.env.BASE_API_OF_SYS_MANAGE // 配置API路径
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.baseURL = apiRoot
 
// 设置请求的次数
axios.defaults.retry = 2
// 设置请求的间隙(ms)
axios.defaults.retryDelay = 1000
 
// 拦截响应response,并做一些错误处理
axios.interceptors.response.use(function(response) {
  // 对响应数据的全局状态码处理
  const json = response.data
  if (json.state !== '1') {
    switch (json.state) {
      case '2':
        break
      case '3':
        break
      case '4':
        break
      case '5':
        break
      default:
        break
    }
    // this.$Message.warning(json.msg !== "" ? json.msg : json.state);
  }
  return response
}, function axiosRetryInterceptor(err) {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '请求错误'
        break
      case 401:
        err.message = '未授权,请登录'
        break
      case 403:
        err.message = '拒绝访问'
        break
      case 404:
        err.message = `请求地址出错: ${err.response.config.url}`
        break
      case 408:
        err.message = '请求超时'
        break
      case 500:
        err.message = '服务器内部错误'
        break
      case 501:
        err.message = '服务未实现'
        break
      case 502:
        err.message = '网关错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网关超时'
        break
      case 505:
        err.message = 'HTTP版本不受支持'
        break
      default:
    }
    if (err.response.status === 401) {
      var config = err.config
      // If config does not exist or the retry option is not set, reject
      if (!config || !config.retry) return Promise.reject(err)
      // Set the variable for keeping track of the retry count
      config.__retryCount = config.__retryCount || 0
      // Check if we've maxed out the total number of retries
      if (config.__retryCount >= config.retry) {
        // Reject with the error
        return Promise.reject(err)
      }
      // Increase the retry count
      config.__retryCount += 1
 
      // Create new promise to handle exponential backoff
      var backoff = new Promise(function(resolve) {
        /* setTimeout(function () {
                    resolve();
                }, config.retryDelay || 1); */
        // 利用刷新Token代替间隔周期
        getToken(function(token) {
          if (token.access_token) {
            config.headers.Authorization = 'bearer ' + token.access_token;
          }
          resolve()
        })
      })
      // Return the promise in which recalls axios to retry the request
      return backoff.then(function() {
        return axios(config) // 返回的请求若正常还回到最初请求的响应
        // .then(function (response) {
        //     if (this.debug) console.log(response.data);
        //     if (this.debug) console.log(response.status);
        //     if (this.debug) console.log(response.statusText);
        //     if (this.debug) console.log(response.headers);
        //     if (this.debug) console.log(response.config);
        //     return Promise.resolve();
        // });
        // 开启另一请求,则会关闭当前拦截效果
        /* return getToken(function (token) {
                    if (token.access_token) {
                        config.headers.Authorization = "bearer " + token.access_token;
                    }
                    return axios(config)
 
                }); */
      })
    }
  }
  return Promise.reject(err)
})
/**
 * 请求Token
 * @param {*} callback 请求成功回调
 * @param {*} user token请求参数,登录信息
 */
function getToken(callback, user) {
  var srcwin = window.opener || window.parent
  srcwin.postMessage('SUBSYS.ADMIN|GetToken', '*')
 
  setTimeout(function() {
    if (callback) {
      const obj = storeHelper.getStorageObject()
      // console.log('wandan')
      // console.log(obj)
      if (obj && obj.tokenInfo) {
        axios.defaults.headers.common['Authorization'] = 'bearer ' + obj.tokenInfo.access_token
        return callback(obj.tokenInfo)
      }
    }
  }, 2000)
  return
  // ---------------------
}
axios.install = (Vue) => {
  Vue.prototype.$http = axios
  Vue.prototype.$getToken = getToken
  Vue.prototype.$mystore = storeHelper
}
 
/**
 * 封装post请求
 * @param url
 * @param data
 */
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}
 
/**
 * 封装get请求
 * @param url
 * @param data
 */
export function get(url, data) {
  url += '?'
  var objKeys = Object.keys(data)
  for (var i = 0; i < objKeys.length; i++) {
    if (i < objKeys.length - 1) {
      url = url + objKeys[i] + '=' + data[objKeys[i]] + '&'
    } else {
      url = url + objKeys[i] + '=' + data[objKeys[i]]
    }
  }
  return new Promise((resolve, reject) => {
    axios.get(url)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}
 
/**
 * 封装delete请求
 * @param url
 * @param data
 */
export function del(url, data) {
  return new Promise((resolve, reject) => {
    axios.delete(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}
 
/**
 * 封装put请求
 * @param url
 * @param data
 */
export function put(url, data) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

 

localstorageHelper.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const key = 'Admin-Token'
 
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth' // 验权
 
function setStorageObject(_data) {
  // 存储,IE6~7 cookie 其他浏览器HTML5本地存储
  if (window.localStorage) {
    localStorage.setItem(key, JSON.stringify(_data))
    // console.log('设置本地token')
    setToken(_data.tokenInfo.access_token)
  } else {
    setToken(_data.tokenInfo.access_token)
  }
}
 
export default {
  /* data() {
      return this.data;
  } */
  // key: "CMP.WEB.DATA",
  /** 当前用户信息的全部存储对象 */
  data: {
    userInfo: {
      id: 0,
      username: '',
      openId: '',
      authInfo: {
        links: [],
        permissionInfo: {}
      }
    },
    tokenInfo: {
      access_token: '',
      expires_in: '2018-04-28T20:40:47.784363+08:00',
      token_type: 'Bearer'
    }
  },
  /**
   * 获取全部存储对象
   */
  getStorageObject() {
    const _data = window.localStorage ? localStorage.getItem(key) : getToken(key)
    if (_data) {
      this.data = JSON.parse(_data)
    } else {
      this.data = {}
    }
    // this.data = _data
    return this.data
  },
  /** 是否登录状态 */
  isLogin() {
    this.getStorageObject()
    if (!this.data || !this.data.userInfo || !this.data.userInfo.username) {
      return false
    } else {
      return true
    }
  },
  /** 是否注销状态 */
  isLogout() {
    this.getStorageObject()
    if (this.data.userInfo) {
      return false
    } else {
      return true
    }
  },
  /** 删除当前用户存储对象,用于注销 */
  removeStorageObject() {
    // 存储,IE6~7 cookie 其他浏览器HTML5本地存储
    if (window.localStorage) {
      window.localStorage.removeItem(key)
    } else {
      removeToken(key)
    }
  },
  /**
   * 设置token信息对象,需要先获取data.tokenInfo,再修改data.tokenInfo,最后再通过此方法更新
   * @param {JSON} _data tokenInfo
   */
  setTokenInfo(_data) {
    this.data.tokenInfo = _data
    setStorageObject(this.data)
  },
  /**
   * 设置用户信息对象,需要先获取data.userInfo,再修改data.userInfo,最后再通过此方法更新
   * @param {JSON} _data userInfo
   */
  setUserInfo(_data) {
    this.data.userInfo = _data
    setStorageObject(this.data)
  },
  /**
   * 设置用户信息对象,需要先获取data.userInfo,再修改data.userInfo,最后再通过此方法更新
   * @param {JSON} _data userInfo
   */
  setAllInfo(_data) {
    this.data = _data
    setStorageObject(this.data)
  }
 
}

 

posted @   shiweiqianju  阅读(320)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示