axios學(xué)習(xí)教程全攻略
前言
隨著 vuejs 作者尤雨溪發(fā)布消息,不再繼續(xù)維護(hù)vue-resource,并推薦大家使用 axios 開始,axios 被越來越多的人所了解。本來想在網(wǎng)上找找詳細(xì)攻略,突然發(fā)現(xiàn),axios 的官方文檔本身就非常詳細(xì)?。∮羞@個(gè)還要什么自行車??!所以推薦大家學(xué)習(xí)這種庫(kù),最好詳細(xì)閱讀其官方文檔。大概翻譯了一下 axios 的官方文檔,相信大家只要吃透本文再加以實(shí)踐,axios 就是小意思啦??!
如果您覺得本文對(duì)您有幫助,不妨點(diǎn)個(gè)贊或關(guān)注收藏一下,您的鼓勵(lì)對(duì)我非常重要。
axios 簡(jiǎn)介
axios 是一個(gè)基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端,它本身具有以下特征:
- 從瀏覽器中創(chuàng)建 XMLHttpRequest
- 從 node.js 發(fā)出 http 請(qǐng)求
- 支持 Promise API
- 攔截請(qǐng)求和響應(yīng)
- 轉(zhuǎn)換請(qǐng)求和響應(yīng)數(shù)據(jù)
- 取消請(qǐng)求
- 自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
- 客戶端支持防止 CSRF/XSRF
瀏覽器兼容性

引入方式:
$ npm install axios $ cnpm install axios //taobao源 $ bower install axios
或者使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
舉個(gè)栗子:
執(zhí)行 GET 請(qǐng)求
// 向具有指定ID的用戶發(fā)出請(qǐng)求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通過 params 對(duì)象傳遞參數(shù)
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執(zhí)行 POST 請(qǐng)求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執(zhí)行多個(gè)并發(fā)請(qǐng)求
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) {
//兩個(gè)請(qǐng)求現(xiàn)已完成
}));
axios API
可以通過將相關(guān)配置傳遞給 axios 來進(jìn)行請(qǐng)求。
axios(config)
// 發(fā)送一個(gè) POST 請(qǐng)求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios(url[, config])
// 發(fā)送一個(gè) GET 請(qǐng)求 (GET請(qǐng)求是默認(rèn)請(qǐng)求模式)
axios('/user/12345');
請(qǐng)求方法別名
為了方便起見,已經(jīng)為所有支持的請(qǐng)求方法提供了別名。
- 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]])
注意
當(dāng)使用別名方法時(shí),不需要在config中指定url,method和data屬性。
并發(fā)
幫助函數(shù)處理并發(fā)請(qǐng)求。
- axios.all(iterable)
- axios.spread(callback)
創(chuàng)建實(shí)例
您可以使用自定義配置創(chuàng)建axios的新實(shí)例。
axios.create([config])
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
實(shí)例方法
可用的實(shí)例方法如下所示。 指定的配置將與實(shí)例配置合并。
- 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]])
請(qǐng)求配置
這些是用于發(fā)出請(qǐng)求的可用配置選項(xiàng)。 只有url是必需的。 如果未指定方法,請(qǐng)求將默認(rèn)為GET。
{
// `url`是將用于請(qǐng)求的服務(wù)器URL
url: '/user',
// `method`是發(fā)出請(qǐng)求時(shí)使用的請(qǐng)求方法
method: 'get', // 默認(rèn)
// `baseURL`將被添加到`url`前面,除非`url`是絕對(duì)的。
// 可以方便地為 axios 的實(shí)例設(shè)置`baseURL`,以便將相對(duì) URL 傳遞給該實(shí)例的方法。
baseURL: 'https://some-domain.com/api/',
// `transformRequest`允許在請(qǐng)求數(shù)據(jù)發(fā)送到服務(wù)器之前對(duì)其進(jìn)行更改
// 這只適用于請(qǐng)求方法'PUT','POST'和'PATCH'
// 數(shù)組中的最后一個(gè)函數(shù)必須返回一個(gè)字符串,一個(gè) ArrayBuffer或一個(gè) Stream
transformRequest: [function (data) {
// 做任何你想要的數(shù)據(jù)轉(zhuǎn)換
return data;
}],
// `transformResponse`允許在 then / catch之前對(duì)響應(yīng)數(shù)據(jù)進(jìn)行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `headers`是要發(fā)送的自定義 headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params`是要與請(qǐng)求一起發(fā)送的URL參數(shù)
// 必須是純對(duì)象或URLSearchParams對(duì)象
params: {
ID: 12345
},
// `paramsSerializer`是一個(gè)可選的函數(shù),負(fù)責(zé)序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data`是要作為請(qǐng)求主體發(fā)送的數(shù)據(jù)
// 僅適用于請(qǐng)求方法“PUT”,“POST”和“PATCH”
// 當(dāng)沒有設(shè)置`transformRequest`時(shí),必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
firstName: 'Fred'
},
// `timeout`指定請(qǐng)求超時(shí)之前的毫秒數(shù)。
// 如果請(qǐng)求的時(shí)間超過'timeout',請(qǐng)求將被中止。
timeout: 1000,
// `withCredentials`指示是否跨站點(diǎn)訪問控制請(qǐng)求
// should be made using credentials
withCredentials: false, // default
// `adapter'允許自定義處理請(qǐng)求,這使得測(cè)試更容易。
// 返回一個(gè)promise并提供一個(gè)有效的響應(yīng)(參見[response docs](#response-api))
adapter: function (config) {
/* ... */
},
// `auth'表示應(yīng)該使用 HTTP 基本認(rèn)證,并提供憑據(jù)。
// 這將設(shè)置一個(gè)`Authorization'頭,覆蓋任何現(xiàn)有的`Authorization'自定義頭,使用`headers`設(shè)置。
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// “responseType”表示服務(wù)器將響應(yīng)的數(shù)據(jù)類型
// 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
//`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress`允許處理上傳的進(jìn)度事件
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做任何你想要做的
},
// `onDownloadProgress`允許處理下載的進(jìn)度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength`定義允許的http響應(yīng)內(nèi)容的最大大小
maxContentLength: 2000,
// `validateStatus`定義是否解析或拒絕給定的promise
// HTTP響應(yīng)狀態(tài)碼。如果`validateStatus`返回`true`(或被設(shè)置為`null` promise將被解析;否則,promise將被
// 拒絕。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects`定義在node.js中要遵循的重定向的最大數(shù)量。
// 如果設(shè)置為0,則不會(huì)遵循重定向。
maxRedirects: 5, // 默認(rèn)
// `httpAgent`和`httpsAgent`用于定義在node.js中分別執(zhí)行http和https請(qǐng)求時(shí)使用的自定義代理。
// 允許配置類似`keepAlive`的選項(xiàng),
// 默認(rèn)情況下不啟用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy'定義代理服務(wù)器的主機(jī)名和端口
// `auth`表示HTTP Basic auth應(yīng)該用于連接到代理,并提供credentials。
// 這將設(shè)置一個(gè)`Proxy-Authorization` header,覆蓋任何使用`headers`設(shè)置的現(xiàn)有的`Proxy-Authorization` 自定義 headers。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// “cancelToken”指定可用于取消請(qǐng)求的取消令牌
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}
使用 then 時(shí),您將收到如下響應(yīng):
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);
});
配置默認(rèn)值
您可以指定將應(yīng)用于每個(gè)請(qǐng)求的配置默認(rèn)值。
全局axios默認(rèn)值
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
自定義實(shí)例默認(rèn)值
//在創(chuàng)建實(shí)例時(shí)設(shè)置配置默認(rèn)值
var instance = axios.create({
baseURL:'https://api.example.com'
});
//在實(shí)例創(chuàng)建后改變默認(rèn)值
instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;
配置優(yōu)先級(jí)順序
配置將與優(yōu)先順序合并。 順序是lib / defaults.js中的庫(kù)默認(rèn)值,然后是實(shí)例的defaults屬性,最后是請(qǐng)求的config參數(shù)。 后者將優(yōu)先于前者。 這里有一個(gè)例子。
//使用庫(kù)提供的配置默認(rèn)值創(chuàng)建實(shí)例
//此時(shí),超時(shí)配置值為`0`,這是庫(kù)的默認(rèn)值
var instance = axios.create();
//覆蓋庫(kù)的超時(shí)默認(rèn)值
//現(xiàn)在所有請(qǐng)求將在超時(shí)前等待2.5秒
instance.defaults.timeout = 2500;
//覆蓋此請(qǐng)求的超時(shí),因?yàn)樗佬枰荛L(zhǎng)時(shí)間
instance.get('/ longRequest',{
timeout:5000
});
攔截器
你可以截取請(qǐng)求或響應(yīng)在被 then 或者 catch 處理之前
//添加請(qǐng)求攔截器
axios.interceptors.request.use(function(config){
//在發(fā)送請(qǐng)求之前做某事
return config;
},function(error){
//請(qǐng)求錯(cuò)誤時(shí)做些事
return Promise.reject(error);
});
//添加響應(yīng)攔截器
axios.interceptors.response.use(function(response){
//對(duì)響應(yīng)數(shù)據(jù)做些事
return response;
},function(error){
//請(qǐng)求錯(cuò)誤時(shí)做些事
return Promise.reject(error);
});
如果你以后可能需要?jiǎng)h除攔截器。
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
你可以將攔截器添加到axios的自定義實(shí)例。
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
處理錯(cuò)誤
axios.get('/ user / 12345')
.catch(function(error){
if(error.response){
//請(qǐng)求已發(fā)出,但服務(wù)器使用狀態(tài)代碼進(jìn)行響應(yīng)
//落在2xx的范圍之外
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
//在設(shè)置觸發(fā)錯(cuò)誤的請(qǐng)求時(shí)發(fā)生了錯(cuò)誤
console.log('Error',error.message);
}}
console.log(error.config);
});
您可以使用validateStatus配置選項(xiàng)定義自定義HTTP狀態(tài)碼錯(cuò)誤范圍。
axios.get('/ user / 12345',{
validateStatus:function(status){
return status < 500; //僅當(dāng)狀態(tài)代碼大于或等于500時(shí)拒絕
}}
})
消除
您可以使用取消令牌取消請(qǐng)求。
axios cancel token API基于可取消的promise提議,目前處于階段1。
您可以使用CancelToken.source工廠創(chuàng)建一個(gè)取消令牌,如下所示:
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 {
// 處理錯(cuò)誤
}
});
//取消請(qǐng)求(消息參數(shù)是可選的)
source.cancel('操作被用戶取消。');
您還可以通過將執(zhí)行器函數(shù)傳遞給CancelToken構(gòu)造函數(shù)來創(chuàng)建取消令牌:
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/ user / 12345',{
cancelToken:new CancelToken(function executor(c){
//一個(gè)執(zhí)行器函數(shù)接收一個(gè)取消函數(shù)作為參數(shù)
cancel = c;
})
});
// 取消請(qǐng)求
clear();
注意:您可以使用相同的取消令牌取消幾個(gè)請(qǐng)求。
使用application / x-www-form-urlencoded格式
默認(rèn)情況下,axios將JavaScript對(duì)象序列化為JSON。 要以應(yīng)用程序/ x-www-form-urlencoded格式發(fā)送數(shù)據(jù),您可以使用以下選項(xiàng)之一。
瀏覽器
在瀏覽器中,您可以使用URLSearchParams API,如下所示:
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
請(qǐng)注意,所有瀏覽器都不支持URLSearchParams,但是有一個(gè)polyfill可用(確保polyfill全局環(huán)境)。
或者,您可以使用qs庫(kù)對(duì)數(shù)據(jù)進(jìn)行編碼:
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });
Node.js
在node.js中,可以使用querystring模塊,如下所示:
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' });
你也可以使用qs庫(kù)。
Promise
axios 依賴本機(jī)要支持ES6 Promise實(shí)現(xiàn)。 如果您的環(huán)境不支持ES6 Promises,您可以使用polyfill。
TypeScript
axios包括TypeScript定義。
import axios from 'axios';
axios.get('/user?ID=12345');
axios在很大程度上受到Angular提供的$http服務(wù)的啟發(fā)。 最終,axios努力提供一個(gè)在Angular外使用的獨(dú)立的$http-like服務(wù)。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
js實(shí)現(xiàn)每日自動(dòng)換一張圖片的方法
這篇文章主要介紹了js實(shí)現(xiàn)每日自動(dòng)換一張圖片的方法,涉及javascript操作圖片與日期的相關(guān)技巧,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下2015-05-05

