Vue

官网只介绍了如何引入axios,这里是设置全局引入

npm下载axios:

1
npm install axios --save

全局引入axios

在main.js中加入如下代码:

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

例子

添加之后就能在vue文件methods中使用$ajax,例:

执行 GET 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  axios.get('/user?ID=12345')
.then(function (response) {
console.log(response); //回调函数
})
.catch(function (error) {
console.log(error); //请求失败
});

// 可选地,上面的请求可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

执行POST请求

1
2
3
4
5
6
7
8
9
10
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

axios API

可以通过向 axios 传递相关配置来创建请求

1
2
3
4
5
6
7
8
9
10
11
12
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
//axios(url[, config])
// 发送 GET 请求(默认的方法)
axios('/user/12345');

axios跨域问题

在config/index.js文件中找到proxyTable{},在括号中添加:

1
2
3
4
5
6
7
8
9
10
'/api': {
target: 'http://localhost:8080/',//设置你调用的接口域名和端口号 别忘了加http
changeOrigin: true,//如果需要跨域
pathRewrite: {
'^/api': '/'
//这里理解成用面的地址,
//后面组件中我们掉接口时直接用api代替 比如我要调
//用'http://425.0.100.100:8888/user/add',直接写‘/api/user/add’即可
}
}

但是这样处理有个问题啊,只能在开发环境使用。真正线上时还是需要封装一下

封装axios

在一些大型项目中会封装axios,并且添加拦截器。在src下创建目录utils,在utils下创建js文件fetch.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
import axios from 'axios'

Date.prototype.Format = function (fmt) {
let o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
}
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
return fmt
}
// respone拦截器
axios.interceptors.response.use(response => {
return response.data
}, error => {
return error.data
})
axios.defaults.withCredentials = false

function checkStatus(response) {
// loading
// 如果http状态码正常,则直接返回数据
if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
return response
// 如果不需要除了data之外的数据,可以直接 return response.data
}
// 异常状态下,把错误信息返回去
return {
status: -404,
msg: '网络异常'
}
}

function checkCode(res) {
// 如果code异常(这里已经包括网络错误,服务器错误,后端抛出的错误),可以弹出一个错误提示,告诉用户
if (res.status === -404) {
console.log(res.msg)
}
if (res.data && (!res.data.success)) {
// alert(res.data.error_msg)
}
// console.log('loadding')
return res
}

function timestampToTime(timestamp) {
let date = new Date(timestamp),
Y = date.getFullYear() + '-',
M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
D = date.getDate() + ' ',
h = date.getHours() + ':',
m = date.getMinutes() + ':',
s = date.getSeconds()
return Y + M + D + h + m + s
}

export default {
post(url, data) {
return axios({
method: 'post',
url,
//data: qs.stringify(data),
data,
timeout: 15000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
'content-type': 'application/json;charset=UTF-8'
}
}).then(
(response) => {
return response
}
).then(
(res) => {
return res
}
)
},

upload(url, data) {
let form = new FormData()
Object.keys(data).forEach(value => {
form.append(value, data[value])
})
return axios({
method: 'post',
// baseURL: process.env.BASE_API,
url,
data,
transformRequest: [function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}],
timeout: 15000,
headers: {
// 'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(
(response) => {
return response
}
).then(
(res) => {
return res
}
)
},

get(url, params) {
return axios({
method: 'get',
// baseURL: process.env.BASE_API,
url,
params, // get 请求时带的参数
timeout: 15000
}).then(
(response) => {
return response
}
).then(
(res) => {
return res
}
)
},
put(url, data) {
return axios({
method: 'put',
baseURL: process.env.BASE_API,
url,
data,
timeout: 15000
}).then(
(response) => {
return response
}
).then(
(res) => {
return res
}
)
},
time(tamp) {
return timestampToTime(tamp)
}
}

然后再main.js中加入以下代码:

1
2
3
4
5
6
import fetch from './utils/fetch'

const extend = Vue.prototype
extend.$post = fetch.post
extend.$get = fetch.get
extend.$form = fetch.form

然后再vue文件使用的时候就很方便了:

1
2
3
4
5
6
7
this.$post('http://localhost:8080/Mybatis_war_exploded/upload.do',imageFile)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});