axios 是一個基於Promise 用於瀏覽器和nodejs 的HTTP 用戶端,本文就和大家分享最全的axios攻略,隨著vuejs 作者尤雨溪發布消息,不再繼續維護vue-resource,並推薦大家使用axios 開始,axios 被越來越多的人所了解。本來想在網路上找詳細攻略,突然發現,axios 的官方文件本身就非常詳細!所以推薦大家學習這種函式庫,最好詳細閱讀其官方文件。大概翻譯了一下 axios 的官方文檔,相信大家只要吃透本文再加以實踐,axios 就是小意思啦! !
axios 簡介
axios 是基於Promise 用於瀏覽器和nodejs 的HTTP 用戶端,它本身俱有以下特徵:
從瀏覽器建立XMLHttpRequest
從node.js 發出http 請求
支援Promise API
#攔截請求和回應
轉換請求和回應資料
#取消請求
自動轉換JSON資料
用戶端支援防止 CSRF/XSRF
瀏覽器相容性
引入方式:
1 2 3 4 5 | $ npm install axios
$ cnpm install axios
$ bower install axios
或者使用cdn:
<script src= "https://unpkg.com/axios/dist/axios.min.js" ></script>
|
登入後複製
舉例:
執行GET 請求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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);
});
|
登入後複製
1 2 3 4 5 6 7 8 9 10 11 12 | function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread( function (acct, perms) {
}));
|
登入後複製
執行多個並發請求
axios API
可以透過將相關配置傳遞給axios 來進行請求。
axios(config)
1 2 3 4 5 6 7 8 9 | axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
|
登入後複製
1 2 | axios('/user/12345');
|
登入後複製
axios(url[, config])
請求方法別名
為了方便起見,已經為所有支援的請求方法提供了別名。
axios.request(config)
axios.get(url [,config])
axios.delete(url [,config])
axios.head(url [,config])
axios.post( url [,data [,config]])
axios.put(url [,data [,config]])
- ##axios. patch(url [,data [,config]])
注意
使用別名方法時,不需要在config中指定url,method和data屬性。
並發
幫助函數處理並發請求。
- axios.all(iterable)
- axios.spread(callback)
建立實例
您可以使用自訂設定來建立axios的新實例。
axios.create([config])
1 2 3 4 5 | var instance = axios.create({
baseURL: 'https:
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
|
登入後複製
可用的實例方法如下所示。 指定的配置將與實例配置合併。 實例方法
axios#request(config)
axios#get(url [,config])
axios#delete(url [,config])
axios #head(url [,config])
axios#post(url [,data [,config]])
axios#put(url [,data [,config]])
axios#patch( url [,data [,config]])
請求設定
這些是用於發出請求的可用設定選項。 只有url是必需的。 如果未指定方法,請求將預設為GET。
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 | {
url: '/user',
method: 'get',
baseURL: 'https:
transformRequest: [ function (data) {
return data;
}],
transformResponse: [ function (data) {
return data;
}],
headers: {'X-Requested-With': 'XMLHttpRequest'},
params: {
ID: 12345
},
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
data: {
firstName: 'Fred'
},
timeout: 1000,
withCredentials: false,
adapter: function (config) {
},
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
responseType: 'json',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
onUploadProgress: function (progressEvent) {
},
onDownloadProgress: function (progressEvent) {
},
maxContentLength: 2000,
validateStatus: function (status) {
return status >= 200 && status < 300;
},
maxRedirects: 5,
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
cancelToken: new CancelToken( function (cancel) {
})
}
|
登入後複製
1 2 3 4 5 6 7 8 | axios.get('/user/12345')
.then( function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
|
登入後複製
配置預設值使用 then 時,您將收到以下回應:
您可以指定將套用於每個請求的設定預設值。
全域axios預設值
1 2 3 | axios.defaults.baseURL = 'https:
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
|
登入後複製
1 2 3 4 5 6 7 | var instance = axios.create({
baseURL:'https:
});
instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;
|
登入後複製
自訂實例預設值
#配置優先順序
配置將與優先順序合併。 順序是lib / defaults.js中的函式庫預設值,然後是實例的defaults屬性,最後是請求的config參數。 後者將優先於前者。 這裡有一個例子。
1 2 3 4 5 6 7 8 9 10 11 12 | var instance = axios.create();
instance.defaults.timeout = 2500;
instance.get('/ longRequest',{
timeout:5000
});
|
登入後複製
攔截器
你可以截取請求或回應在被then 或catch 處理之前
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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);
});
|
登入後複製
1 2 | var myInterceptor = axios.interceptors.request. use ( function () { });
axios.interceptors.request.eject(myInterceptor);
|
登入後複製
你可以將攔截器加到axios的自訂實例。如果你以後可能需要刪除攔截器。
1 2 | var instance = axios.create();
instance.interceptors.request. use ( function () { });
|
登入後複製
處理錯誤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | axios.get('/ user / 12345')
. catch ( function (error){
if (error.response){
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);
});
|
登入後複製
1 2 3 4 5 | axios.get('/ user / 12345',{
validateStatus: function (status){
return status < 500;
}}
})
|
登入後複製
消除您可以使用validateStatus配置選項定義自訂HTTP狀態碼錯誤範圍。
您可以使用取消令牌取消請求。
axios cancel token API基於可取消的promise提議,目前處於階段1。
您可以使用CancelToken.source工廠建立一個取消令牌,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}). catch ( function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
}
});
source.cancel('操作被用户取消。');
|
登入後複製
1 2 3 4 5 6 7 8 9 10 11 12 | var CancelToken = axios.CancelToken;
var cancel;
axios.get('/ user / 12345',{
cancelToken: new CancelToken( function executor(c){
cancel = c;
})
});
clear();
|
登入後複製
注意:您可以使用相同的取消令牌取消幾個請求。
您也可以透過將執行器函數傳遞給CancelToken建構子來建立取消令牌:
使用application / x-www-form-urlencoded格式
##預設情況下,axios將JavaScript物件序列化為JSON。 要以應用程式/ x-www-form-urlencoded格式發送數據,您可以使用以下選項之一。
浏览器
在浏览器中,您可以使用URLSearchParams API,如下所示:
1 2 3 4 | var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
|
登入後複製
或者,您可以使用qs库对数据进行编码:请注意,所有浏览器都不支持URLSearchParams,但是有一个polyfill可用(确保polyfill全局环境)。
1 2 | var qs = require ('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });
|
登入後複製
在node.js中,可以使用querystring模块,如下所示:Node.js
1 2 | var querystring = require ('querystring');
axios.post('http:
|
登入後複製
Promise你也可以使用qs库。
axios 依赖本机要支持ES6 Promise实现。 如果您的环境不支持ES6 Promises,您可以使用polyfill。
TypeScript
axios包括TypeScript定义。
1 2 | import axios from 'axios';
axios.get('/user?ID=12345');
|
登入後複製
axios在很大程度上受到Angular提供的$http服务的启发。 最终,axios努力提供一个在Angular外使用的独立的$http-like服务。
学完本文相信大家对axios更加深入了解了吧,赶紧收藏起来吧。
相关推荐:
vue配置axios的方法步骤示例
关于VueJs 搭建Axios接口请求工具分析
浅谈axios中的get,post方法介绍
以上是最全的axios攻略的詳細內容。更多資訊請關注PHP中文網其他相關文章!