1
|
|
1
2
3
4
5
6
7
8
9
10
|
// axios 請求 在main.js里邊寫入
import
Axios from
'axios'
// 配置請求信息
var
$http = Axios.create({
baseURL:
'配置路徑'
,
timeout:
'3000'
,
//超時時間
headers: {
'X-Custom-Header'
:
'foobar'
}
//請求頭
})
Vue.prototype.$http = $http
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// 方法調用,回調,post , 基於es6 promise
methods: {
getNum:
function
() {
var
data = { TenantID:
"0"
}
this
.$http.post(
"請求路徑-方法1"
, data ) .then(res => {
console.log(res)
//返回方法1的值
var
data1 = { TenantID: res.data.Code }
//方法1 的返回值作為參數傳遞 res.data.Code
this
.$http.post(
"請求路徑-方法2"
, data1 )
.then(res1 => {
console.log(res.data)
//同樣可以使用方法1的返回值
console.log(res1)
//返回方法2的值
})
})
.
catch
(
function
(error) {
console.log(error)
})
}
//需要使用箭頭函數,否則 this.$http 中的this 指向window,會報 $http undefined
//另外也可以在當前組件 import axios from 'axios' 引入axios 包
//將 this.$http 替換 為 axios 結果一樣
|
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
|
axios 攔截器
你可以截取請求或響應在被 then 或者
catch
處理之前
//添加請求攔截器
axios.interceptors.request.use(
function
(config){
//在發送請求之前做某事
return
config;
},
function
(error){
//請求錯誤時做些事
return
Promise.reject(error);
});
//添加響應攔截器
axios.interceptors.response.use(
function
(response){
//對響應數據做些事
return
response;
},
function
(error){
//請求錯誤時做些事
return
Promise.reject(error);
});<br>
以后可能需要刪除攔截器。
var
myInterceptor = axios.interceptors.request.use(
function
() {
/*...*/
});
axios.interceptors.request.eject(myInterceptor);<br>
你可以將攔截器添加到axios的自定義實例。
var
instance = axios.create();
instance.interceptors.request.use(
function
() {
/*...*/
});<br>
處理錯誤
axios.get(
'/ user / 12345'
)
.
catch
(
function
(error){
if
(error.response){
//請求已發出,但服務器使用狀態代碼進行響應
//落在2xx的范圍之外
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
else
{
//在設置觸發錯誤的請求時發生了錯誤
console.log(
'Error'
,error.message);
}}
console.log(error.config);
});
您可以使用validateStatus配置選項定義自定義HTTP狀態碼錯誤范圍。
axios.get(
'/ user / 12345'
,{
validateStatus:
function
(status){
return
status < 500;
//僅當狀態代碼大於或等於500時拒絕
}}
})
|