1. 安裝axios
在項目下執行npm install axios。
之后在main.js中,添加:
|
1
2
3
4
|
import axios from
'axios'
//引入
//Vue.use(axios) axios不能用use 只能修改原型鏈
Vue.prototype.$axios = axios
|
2. 發送GET請求
axios封裝了get方法,傳入請求地址和請求參數,就可以了,同樣支持Promise。
|
1
2
3
4
5
6
7
8
9
10
|
//不帶參數的get請求
let url =
"..."
this
.$axios.get(url)
.then((res) => {
console.log(res)
//返回的數據
})
.
catch
((err) => {
console.log(err)
//錯誤信息
})
|
不過它的參數需要寫在params屬性下,也就是:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
//帶參數的get請求
let url =
"...getById"
this
.$axios.get(url, {
params: {
id: 1
}
})
.then((res) => {
console.log(res)
//返回的數據
})
.
catch
((err) => {
console.log(err)
//錯誤信息
})
|
2. 發送post請求
與上面相同,就是參數不需要寫在params屬性下了,即:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
//帶參數的post請求
let url =
"...getById"
let data = {
id: 1
}
this
.$axios.post(url, data)
.then((res) => {
console.log(res)
//返回的數據
})
.
catch
((err) => {
console.log(err)
//錯誤信息
})
|
3. 經典寫法
axios也可以用jQ的寫法,不過回調函數還是Promise的寫法,如:
|
1
2
3
4
5
6
7
8
9
10
|
this
.$axios({
method:
'post'
,
url:
'...'
,
data: {
firstName:
'Fred'
,
lastName:
'Flintstone'
}
}).then((res) => {
console.log(res)
})
|
設置form-data請求格式
我用默認的post方法發送數據的時候發現后端獲取不到數據,然而在network中看到參數是的確傳出去的了。而且用postman測試的時候也是可以的,比較了下兩個的不同發現是postman使用的是form-data格式,於是用form-data格式再次請求,發現OJBK
在查找設置請求格式的時候花了點時間,網上的方案有好幾個,這個我親測成功,發上來。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import axios from
"axios"
//引入
//設置axios為form-data
axios.defaults.headers.post[
'Content-Type'
] =
'application/x-www-form-urlencoded'
;
axios.defaults.headers.get[
'Content-Type'
] =
'application/x-www-form-urlencoded'
;
axios.defaults.transformRequest = [
function
(data) {
let ret =
''
for
(let it
in
data) {
ret += encodeURIComponent(it) +
'='
+ encodeURIComponent(data[it]) +
'&'
}
return
ret
}]
//然后再修改原型鏈
Vue.prototype.$axios = axios
|
