在vue中对axios进行二次封装

为aixos配置统一请求地址,统一请求头等。

封装

src下新建axios/axios.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
import axios from 'axios';
import router from "../router"
import Tools from '@/components/Tools/index';
import store from '../store'

let token = '';
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

//添加请求拦截器
axios.interceptors.request.use(
config => {
let api_token = JSON.parse(sessionStorage.getItem('api_token')!)
if (api_token) {
token = api_token
}
config.headers.common['Authorization'] = 'Bearer ' + token;
return config;
},
error => {
return Promise.reject(error);
}
);
//添加响应拦截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
return Promise.resolve(error.response);
}
);
axios.defaults.baseURL = process.env.VUE_APP_BASEURL

axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers.put["Content-Type"] = "application/json";
axios.defaults.headers.put["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers.delete["Content-Type"] = "application/json";
axios.defaults.headers.delete["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.timeout = 10000;
function checkStatus(response ) {
return new Promise((resolve, reject) => {
if (
response &&
(response.status === 200 ||
response.status === 304 ||
response.status === 400)
) {
resolve(response.data);
} else {
reject({
status: response.status,
message: response.data.message,
error: response.data.errors[Object.keys(response.data.errors)[0]][0]
});
}
});
}
export default {
post(url, params) {
return axios({
method: "post",
url,
data: params
}).then(response => {
return checkStatus(response);
});
},
get(url, params) {
return axios({
method: "get",
url,
params
}).then(response => {
return checkStatus(response);
});
},
put(url, params) {
return axios({
method: "put",
url,
data: params
}).then(response => {
return checkStatus(response);
});
},
delete(url, params) {
return axios({
method: "delete",
url,
data: params
}).then(response => {
return checkStatus(response);
});
}
};

使用

首先在main.js中进行引用

1
2
3
import axios from './axios/axios'

Vue.prototype.$axios = axios;

然后在我们要使用的地方

1
2
3
this.$axios.post('接口地址',{}).then(res=>{

})

将uni-request进行axios化封装
在flutter中优雅的封装网络请求

文章作者: Joker
文章链接: https://qytayh.github.io/2020/08/%E5%9C%A8vue%E4%B8%AD%E5%AF%B9axios%E8%BF%9B%E8%A1%8C%E4%BA%8C%E6%AC%A1%E5%B0%81%E8%A3%85/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Joker's Blog