axios封装


封装包含以下方面:

  • 设置请求超时时间
  • 根据环境项目设置请求路径
  • 设置请求拦截,自动添加token
  • 设置响应拦截,对响应的状态码或者数据进行格式化
  • 增添请求队列,实现loading效果
  • 维护取消请求token,在页面切换时通过导航首位可以取消上个页面中正在发送的请求
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
import axios from 'axios'

class HttpRequest{
constructor(){
this.baseURL = process.enV.NODE_ENV === 'production'? '/' : 'http://localhost:8001'
this.timeout = 3000
// loading需要加
this.queue = {}// 专门用于维护请求队列的
}

setInterceptor(instance,url){
if(Object.keys(this.queue).length == 0){
// 开loading
}
let token = localStorage.getItem('token')
if(token){
// 每次请求都会携带一个权限访问服务器
config.headers.authorization = token
}
// 可以记录请求的取消函数
let CancelToken = axios.CancelToken
// xhr.abort()终端请求方法
config.cancelToken = new CancelToken(c=>{
store.commit(Types.SET_TOKEN,c)
})
this.queue[url] = true
return config
}

request(options){// 通过requirest方法来进行请求操作
// 每次请求可以创建一个新的实例,如果业务不复杂你可以不创建实例,直接使用axios
let instance = axios.create()
let config = {
baseURL: this.baseURL,
timeout: this.timeout,
...options
}
this.setInterceptor(instance,config.url)
return instance(config) // 产生的是一个promise axios
}

get(url,data = {}){// url,{} axios.get('/xxx',{params:xxx})
return this.request({
url,
method:'get',
...data
})

}

post(url,data = {}){// axios.post('/xxx',{params:xxx})
return this.request({
url,
method:'get',
data
})

}
}

export default new HttpRequest