vue-axios配置

在Vue项目中,如果没有引入JQuery,那么使用axios来做http请求将是一个不错的选择,因为它相对于ajax不需要引入JQuery包,这样项目就会小很多。

先引入axios依赖包

$ yarn add axios vue-axios

下面,我们来看一下axios的常用基本配置

导入axios,一般我们会在一个公共方法js文件里做一下操作,它通常被命名为util.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
import axios from 'axios'
 
// 全局设置超时时间
axios.defaults.timeout = 20000
 
// 请求路由拦截 一般在此处配置请求头和token
axios.interceptors.request.use(function (config) {
    let token = sessionStorage.getItem("user_token");
    if (config.method == 'get') {
        config.headers = {
            'Content-Type': 'application/json',
            'Authorization': token
        }
        config.data = true
    } else {
        config.headers = {
            'Content-Type': 'application/json',
            'Authorization': token
        }
    }
    return config
}, function (error) {
    return Promise.reject(error)
})
 
// respone拦截器 响应路由拦截 一般在此处做返回错误码的后续操作,比如没有权限跳回登录页
axios.interceptors.response.use(
    response => {
        const res = response.data
        return response
    },
    error => {
        if (error.response.status == 401) { // 没有权限
            Message({
                message: '登录过期,请重新登录!',
                type: 'error'
            })
            window.location.href = '/#/login'
        }
        if (error.response.status == 403) { // 被拒绝访问
            Message({
                message: '您没有此操作的权限!',
                type: 'error'
            })
            window.location.href = '/#/error?code=' + 403
        }
        if (error.response.status == 502) { // 服务器错误
            Message({
                message: '服务器正在发布中,请稍后重试!',
                type: 'error'
            })
            window.location.href = '/#/login'
        }
        return Promise.reject(error)
    }
)
 
axios.defaults.headers.delete['Content-Type'] = 'application/x-www-form-urlencoded' // 单独配置delete的请求头
 
// 以下是几种常用的公共方法
var instance = axios.create({
    headers: { 'content-type': 'multipart/form-data' }
});
 
export default {
    Get(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.get(url, {
                params
            }).then(res => {
                resolve(res.data)
            }).catch(err => {
                reject(err.data)
            })
        })
    },
    Getfile(url, params = {}, name) {
        return new Promise((resolve, reject) => {
            axios.get(url, {
                params,
                responseType: 'blob'
            }).then(res => {
                resolve(res.data)
                let blob = new Blob([res.data], {
                    type: 'application/vnd.ms-excel'
                })
                // 先转码再解码
                let fileName
                // let fileName = decodeURI(escape(res.headers['content-disposition'].split('filename=')[1]))
                if (name && name != '' && name != null) {
                    fileName = name
                } else {
                    fileName = decodeURI(res.headers['content-disposition'].split('filename=')[1])
                }
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, fileName)
                } else {
                    var link = document.createElement('a')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = fileName
                    link.click()
                    Message({
                        message: '下载成功!',
                        type: 'success'
                    })
                    //释放内存
                    window.URL.revokeObjectURL(link.href)
                }
            }).catch(err => {
                console.log('err', err)
                if (err) {
                    Message({
                        message: '下载失败!',
                        type: 'error'
                    })
                }
                reject(err.data)
            })
        })
    },
    Postfile(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url,
                params,
                { responseType: 'blob' }
            ).then(res => {
                resolve(res.data)
                let blob = new Blob([res.data], {
                    type: 'application/vnd.ms-excel'
                })
                // 先转码再解码
                // let fileName = decodeURI(escape(res.headers['content-disposition'].split('filename=')[1]))
                let fileName = decodeURI(res.headers['content-disposition'].split('filename=')[1])
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, fileName)
                } else {
                    var link = document.createElement('a')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = fileName
                    link.click()
                    Message({
                        message: '下载成功!',
                        type: 'success'
                    })
                    //释放内存
                    window.URL.revokeObjectURL(link.href)
                }
            }).catch(err => {
                if (err) {
                    Message({
                        message: '下载失败!',
                        type: 'error'
                    })
                }
                reject(err.data)
            })
        })
    },
    Post(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, params)
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err.data)
                })
        })
    },
    Postform(url, data = {}) {
        return new Promise((resolve, reject) => {
            instance.post(url, data)
                .then(res => {
                    resolve(res.data);
                }, err => {
                    reject(err.data)
                })
        })
    },
    Put(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.put(url, params)
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err.data)
                })
        })
    },
    Delete(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.delete(url, data)
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err.data)
                })
        })
    },
}

  

 

posted @   心心眼  阅读(543)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示