vue中axios的基本使用

(一)安装: npm install –save axios

(二)引入:

在文件main.js中:

1
2
import axios from 'axios';
Vue.prototype.$axios=axios;

(三)在vue文件中引用

(1)基本的get方法

1
2
3
4
5
6
7
8
9
10
11
getMsg() {
let that = this;
that.$axios
.get(this.$global_msg.address)
.then((res) => {
console.log(res.data);
})
.catch(function(err) {
console.log(err);
});
}

(2) post方法示例 (如需设置header)

1
2
3
4
5
6
7
8
9
10
this.axios({
method: "POST",
url: this.$global_msg.address,
data: obj,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(res) {
console.log(res);
});

(四)axios拦截器

axios拦截器分为http request请求拦截器和http response 响应拦截器。请求拦截器规定了在发送请求前需要做的事;响应拦截器则是针对返回的状态码进行进一步的操作(比如判断是否需要重新登陆)。下面记录了在VUE项目中如何封装和基本使用。

VUE项目,按以下路径新建httpService.js文件:src/service/requests/httpService.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
import Vue from "vue";
import message from "ant-design-vue/es/message";
import axios from "axios";
// import {
// Modal
// } from 'ant-design-vue'
import { Toast } from "mint-ui";
// import {
// TokenKey,
// getToken
// } from './auth'
import store from "@/store";
import router from "@/router";

const service = axios.create({
// baseURL: "/api",
baseURL: process.env.VUE_APP_PROXY_HOST,
timeout: 20000 //请求超时
});
// baseURL在.env.development和.env.production中设置,比如在.env.development中:设置:VUE_APP_PROXY_HOST=http://xx.xx.xx.xx:xxxx
VUE_APP_HTML_TITLE="网页名称"。也就是为开发环境增加了基本请求路径,生产环境的设置同理。.env文件中VUE_APP_HOST=xx.xx.xx.xx
VUE_APP_PORT=xxxx
VUE_APP_PROXY_HOST=http://xx.xx.xx.xx:xxxx

let errMessage = "服务忙,请稍后再试";

// 携带 cookie
service.defaults.withCredentials = false;

// http request请求拦截器。发送请求前判断是否带有token。
service.interceptors.request.use(
// 在发送请求之前做以下事:
config => {
if (store.getters.token) {
// 头部携带 token
// config.headers[TokenKey] = getToken() // 获取token
}
let token = window.localStorage.getItem("Authorization");
if (token) {
config.headers.Authorization = token;
}
return config;
},
error => {
// 请求错误时
console.error(error);
return Promise.reject(error);
}
);

// http response 响应拦截器,针对返回的状态码进行进一步的操作。比如判断是否需要重新登陆。
service.interceptors.response.use(
// 在发送请求之后做以下事:
response => {
// 成功请求到了数据
const res = response.data;
if (
response.headers["content-type"] &&
response.headers["content-type"].startsWith("application/json") &&
res.code !== 0
) {
if (res.code === 20003 || res.code === 20004 || res.code === 20005) {
Toast({
message:
"您的登录信息已失效,点击确定重新登录,点击取消继续留在当前页面",
position: "middle",
duration: 3000
});

// 执行登录失效后的回调
// return store.dispatch('user/resetToken')
// .then(() => {
// location.reload()
// })
} else if (res.code == 200 && res.status == "ok") {
return Promise.resolve(res);
} else {
message.error(res.msg || errMessage);
}
return Promise.reject(res);
} else {
// 存储 token,已经启用了 cookie, 该头部字段非必须。适配一些不支持或者禁用了 cookie 的场合。
if (res.data.token) {
store.dispatch("user/setToken", res.data.token);
}
return Promise.resolve(res);
}
},

// 请求错误的处理
error => {
const { response } = error;
if (response.status == 401) {
const paths = window.location.href.split("/");
const path = paths[paths.length - 1];
if (path == "login") {
// 当无法通过身份验证且已跳转到登录时直接返回错误
return Promise.reject(res);
}
if (response.data.code == "401" && response.data.msg[0] == "管") {
// 帐号/密码错误特殊提示
message.error(response.data.msg, 5);
router.push("/login");
return Promise.reject(res);
}
message.error("请重新登录");
router.push("/login");
return Promise.reject(res);
}
message.error(response.data.msg, 5);
return Promise.reject(error);
}
);
export default service;

接下来需要引用httpService.js,在main.js中,增加以下代码,这样可以在所有组件中直接使用:

1
2
import axios from "./service/requests/httpService";
Vue.prototype.$axios = axios;

在组件中使用:(以get请求为例)

1
2
3
4
5
6
7
8
9
10
11
12
13
getMsg() {
const _this = this;
_this.$axios
.get("/home/message")
.then(function(res) {
if (res.code == 200 && res.status == "ok") {
// do something here
}
})
.catch(function(res) {
return;
});
}