詳解vue axios中文文檔
axios中文文檔
在用Vue做開發(fā)的時(shí)候,官方推薦的前后端通信插件是axios,Github上axios的文檔雖然詳細(xì),但是卻是英文版.現(xiàn)在發(fā)現(xiàn)有個(gè)axios的中文文檔,于是就轉(zhuǎn)載過來了!
原文地址 : https://github.com/mzabriskie/axios
簡介
版本:v0.16.1
基于http客戶端的promise,面向?yàn)g覽器和nodejs
特色
- 瀏覽器端發(fā)起XMLHttpRequests請求
- node端發(fā)起http請求
- 支持Promise API
- 攔截請求和返回
- 轉(zhuǎn)化請求和返回(數(shù)據(jù))
- 取消請求
- 自動(dòng)轉(zhuǎn)化json數(shù)據(jù)
- 客戶端支持抵御XSRF(跨站請求偽造)
安裝
使用npm:
$ npm i axios
使用 bower
$ bower instal axios
使用cdn
<!--國內(nèi)bootCDN--> <script src="https://cdn.bootcss.com/axios/0.16.0/axios.min.js"></script>
示例
發(fā)起一個(gè)GET請求
//發(fā)起一個(gè)user請求,參數(shù)為給定的ID axios.get('/user?ID=1234') .then(function(respone){ 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) });
發(fā)起一個(gè)POST請求
axios.post('/user',{ firstName:'friend', lastName:'Flintstone' }) .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error); });
發(fā)起一個(gè)多重并發(fā)請求
function getUserAccount(){ return axios.get('/user/12345'); } function getUserPermissions(){ return axios.get('/user/12345/permissions'); } axios.all([getUerAccount(),getUserPermissions()]) .then(axios.spread(function(acc,pers){ //兩個(gè)請求現(xiàn)在都完成 }));
axios API
可以對axios進(jìn)行一些設(shè)置來生成請求。
axios(config)
//發(fā)起 POST請求 axios({ method:'post',//方法 url:'/user/12345',//地址 data:{//參數(shù) firstName:'Fred', lastName:'Flintstone' } });
//通過請求獲取遠(yuǎn)程圖片 axios({ method:'get', url:'http://bit.ly/2mTM3Ny', responseType:'stream' }) .then(function(response){ response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) })
axios(url[,config])
//發(fā)起一個(gè)GET請求 axios('/user/12345/);
請求方法的重命名。
為了方便,axios提供了所有請求方法的重命名支持
- axios.request(config)
- axios.get(url[,config])
- axios.delete(url[,config])
- axios.head(url[,config])
- axios.options(url[,config])
- axios.post(url[,data[,config]])
- axios.put(url[,data[,config]])
- axios.patch(url[,data[,config]])
注意
當(dāng)時(shí)用重命名方法時(shí)url,method,以及data屬性不需要在config中指定。
并發(fā) Concurrency
有用的方法
- axios.all(iterable)
- axios.spread(callback)
創(chuàng)建一個(gè)實(shí)例
你可以使用自定義設(shè)置創(chuàng)建一個(gè)新的實(shí)例
axios.create([config])
var instance = axios.create({ baseURL:'http://some-domain.com/api/', timeout:1000, headers:{'X-Custom-Header':'foobar'} });
實(shí)例方法
下面列出了一些實(shí)例方法。具體的設(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]])
Requese Config請求設(shè)置
以下列出了一些請求時(shí)的設(shè)置選項(xiàng)。只有url是必須的,如果沒有指明method的話,默認(rèn)的請求方法是GET.
{ //`url`是服務(wù)器鏈接,用來請求 url:'/user', //`method`是發(fā)起請求時(shí)的請求方法 method:`get`, //`baseURL`如果`url`不是絕對地址,那么將會加在其前面。 //當(dāng)axios使用相對地址時(shí)這個(gè)設(shè)置非常方便 //在其實(shí)例中的方法 baseURL:'http://some-domain.com/api/', //`transformRequest`允許請求的數(shù)據(jù)在傳到服務(wù)器之前進(jìn)行轉(zhuǎn)化。 //這個(gè)只適用于`PUT`,`GET`,`PATCH`方法。 //數(shù)組中的最后一個(gè)函數(shù)必須返回一個(gè)字符串或者一個(gè)`ArrayBuffer`,或者`Stream`,`Buffer`實(shí)例,`ArrayBuffer`,`FormData` transformRequest:[function(data){ //依自己的需求對請求數(shù)據(jù)進(jìn)行處理 return data; }], //`transformResponse`允許返回的數(shù)據(jù)傳入then/catch之前進(jìn)行處理 transformResponse:[function(data){ //依需要對數(shù)據(jù)進(jìn)行處理 return data; }], //`headers`是自定義的要被發(fā)送的頭信息 headers:{'X-Requested-with':'XMLHttpRequest'}, //`params`是請求連接中的請求參數(shù),必須是一個(gè)純對象,或者URLSearchParams對象 params:{ ID:12345 }, //`paramsSerializer`是一個(gè)可選的函數(shù),是用來序列化參數(shù) //例如:(https://ww.npmjs.com/package/qs,http://api.jquery.com/jquery.param/) paramsSerializer: function(params){ return Qs.stringify(params,{arrayFormat:'brackets'}) }, //`data`是請求提需要設(shè)置的數(shù)據(jù) //只適用于應(yīng)用的'PUT','POST','PATCH',請求方法 //當(dāng)沒有設(shè)置`transformRequest`時(shí),必須是以下其中之一的類型(不可重復(fù)?): //-string,plain object,ArrayBuffer,ArrayBufferView,URLSearchParams //-僅瀏覽器:FormData,File,Blob //-僅Node:Stream data:{ firstName:'fred' }, //`timeout`定義請求的時(shí)間,單位是毫秒。 //如果請求的時(shí)間超過這個(gè)設(shè)定時(shí)間,請求將會停止。 timeout:1000, //`withCredentials`表明是否跨網(wǎng)站訪問協(xié)議, //應(yīng)該使用證書 withCredentials:false //默認(rèn)值 //`adapter`適配器,允許自定義處理請求,這會使測試更簡單。 //返回一個(gè)promise,并且提供驗(yàn)證返回(查看[response docs](#response-api)) adapter:function(config){ /*...*/ }, //`auth`表明HTTP基礎(chǔ)的認(rèn)證應(yīng)該被使用,并且提供證書。 //這個(gè)會設(shè)置一個(gè)`authorization` 頭(header),并且覆蓋你在header設(shè)置的Authorization頭信息。 auth:{ username:'janedoe', password:'s00pers3cret' }, //`responsetype`表明服務(wù)器返回的數(shù)據(jù)類型,這些類型的設(shè)置應(yīng)該是 //'arraybuffer','blob','document','json','text',stream' responsetype:'json', //`xsrfHeaderName` 是http頭(header)的名字,并且該頭攜帶xsrf的值 xrsfHeadername:'X-XSRF-TOKEN',//默認(rèn)值 //`onUploadProgress`允許處理上傳過程的事件 onUploadProgress: function(progressEvent){ //本地過程事件發(fā)生時(shí)想做的事 }, //`onDownloadProgress`允許處理下載過程的事件 onDownloadProgress: function(progressEvent){ //下載過程中想做的事 }, //`maxContentLength` 定義http返回內(nèi)容的最大容量 maxContentLength: 2000, //`validateStatus` 定義promise的resolve和reject。 //http返回狀態(tài)碼,如果`validateStatus`返回true(或者設(shè)置成null/undefined),promise將會接受;其他的promise將會拒絕。 validateStatus: function(status){ return status >= 200 && stauts < 300;//默認(rèn) }, //`httpAgent` 和 `httpsAgent`當(dāng)產(chǎn)生一個(gè)http或者h(yuǎn)ttps請求時(shí)分別定義一個(gè)自定義的代理,在nodejs中。 //這個(gè)允許設(shè)置一些選選個(gè),像是`keepAlive`--這個(gè)在默認(rèn)中是沒有開啟的。 httpAgent: new http.Agent({keepAlive:treu}), httpsAgent: new https.Agent({keepAlive:true}), //`proxy`定義服務(wù)器的主機(jī)名字和端口號。 //`auth`表明HTTP基本認(rèn)證應(yīng)該跟`proxy`相連接,并且提供證書。 //這個(gè)將設(shè)置一個(gè)'Proxy-Authorization'頭(header),覆蓋原先自定義的。 proxy:{ host:127.0.0.1, port:9000, auth:{ username:'cdd', password:'123456' } }, //`cancelTaken` 定義一個(gè)取消,能夠用來取消請求 //(查看 下面的Cancellation 的詳細(xì)部分) cancelToken: new CancelToken(function(cancel){ }) }
返回響應(yīng)概要 Response Schema
一個(gè)請求的返回包含以下信息
{ //`data`是服務(wù)器的提供的回復(fù)(相對于請求) data{}, //`status`是服務(wù)器返回的http狀態(tài)碼 status:200, //`statusText`是服務(wù)器返回的http狀態(tài)信息 statusText: 'ok', //`headers`是服務(wù)器返回中攜帶的headers headers:{}, //`config`是對axios進(jìn)行的設(shè)置,目的是為了請求(request) config:{} }
使用then,你會接受打下面的信息
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); });
使用catch時(shí),或者傳入一個(gè)reject callback作為then的第二個(gè)參數(shù),那么返回的錯(cuò)誤信息將能夠被使用。
默認(rèn)設(shè)置(Config Default)
你可以設(shè)置一個(gè)默認(rèn)的設(shè)置,這設(shè)置將在所有的請求中有效。
全局默認(rèn)設(shè)置 Global axios defaults
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)值 Custom instance default
//當(dāng)創(chuàng)建一個(gè)實(shí)例時(shí)進(jìn)行默認(rèn)設(shè)置 var instance = axios.create({ baseURL:'https://api.example.com' }); //在實(shí)例創(chuàng)建之后改變默認(rèn)值 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
設(shè)置優(yōu)先級 Config order of precedence
設(shè)置(config)將按照優(yōu)先順序整合起來。首先的是在lib/defaults.js中定義的默認(rèn)設(shè)置,其次是defaults實(shí)例屬性的設(shè)置,最后是請求中config參數(shù)的設(shè)置。越往后面的等級越高,會覆蓋前面的設(shè)置。
看下面這個(gè)例子:
//使用默認(rèn)庫的設(shè)置創(chuàng)建一個(gè)實(shí)例, //這個(gè)實(shí)例中,使用的是默認(rèn)庫的timeout設(shè)置,默認(rèn)值是0。 var instance = axios.create(); //覆蓋默認(rèn)庫中timeout的默認(rèn)值 //此時(shí),所有的請求的timeout時(shí)間是2.5秒 instance.defaults.timeout = 2500; //覆蓋該次請求中timeout的值,這個(gè)值設(shè)置的時(shí)間更長一些 instance.get('/longRequest',{ timeout:5000 });
攔截器 interceptors
你可以在請求或者返回被then或者catch處理之前對他們進(jìn)行攔截。
//添加一個(gè)請求攔截器 axios.interceptors.request.use(function(config){ //在請求發(fā)送之前做一些事 return config; },function(error){ //當(dāng)出現(xiàn)請求錯(cuò)誤是做一些事 return Promise.reject(error); }); //添加一個(gè)返回?cái)r截器 axios.interceptors.response.use(function(response){ //對返回的數(shù)據(jù)進(jìn)行一些處理 return response; },function(error){ //對返回的錯(cuò)誤進(jìn)行一些處理 return Promise.reject(error); });
如果你需要在稍后移除攔截器,你可以
var myInterceptor = axios.interceptors.request.use(function(){/*...*/}); axios.interceptors.rquest.eject(myInterceptor);
你可以在一個(gè)axios實(shí)例中使用攔截器
var instance = axios.create(); instance.interceptors.request.use(function(){/*...*/});
錯(cuò)誤處理 Handling Errors
axios.get('user/12345') .catch(function(error){ if(error.response){ //存在請求,但是服務(wù)器的返回一個(gè)狀態(tài)碼 //他們都在2xx之外 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); }else{ //一些錯(cuò)誤是在設(shè)置請求時(shí)觸發(fā)的 console.log('Error',error.message); } console.log(error.config); });
你可以使用validateStatus設(shè)置選項(xiàng)自定義HTTP狀態(tài)碼的錯(cuò)誤范圍。
axios.get('user/12345',{ validateStatus:function(status){ return status < 500;//當(dāng)返回碼小于等于500時(shí)視為錯(cuò)誤 } });
取消 Cancellation
你可以使用cancel token取消一個(gè)請求
axios的cancel token API是基于**cnacelable promises proposal**,其目前處于第一階段。
你可以使用CancelToken.source工廠函數(shù)創(chuàng)建一個(gè)cancel token,如下:
var CancelToken = axios.CancelToken; var source = CancelToken.source(); axios.get('/user/12345', { cancelToken:source.toke }).catch(function(thrown){ if(axiso.isCancel(thrown)){ console.log('Rquest canceled', thrown.message); }else{ //handle error } }); //取消請求(信息參數(shù)設(shè)可設(shè)置的) source.cancel("操作被用戶取消");
你可以給CancelToken構(gòu)造函數(shù)傳遞一個(gè)executor function來創(chuàng)建一個(gè)cancel token:
var CancelToken = axios.CancelToken; var cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c){ //這個(gè)executor 函數(shù)接受一個(gè)cancel function作為參數(shù) cancel = c; }) }); //取消請求 cancel();
注意:你可以使用同一個(gè)cancel token取消多個(gè)請求。
使用 application/x-www-form-urlencoded 格式化
默認(rèn)情況下,axios串聯(lián)js對象為JSON格式。為了發(fā)送application/x-wwww-form-urlencoded格式數(shù)據(jù),
你可以使用一下的設(shè)置。
瀏覽器 Browser
在瀏覽器中你可以如下使用URLSearchParams API:
var params = new URLSearchParams(); params.append('param1','value1'); params.append('param2','value2'); axios.post('/foo',params);
注意:URLSearchParams不支持所有的瀏覽器,但是這里有個(gè)墊片(poly fill)可用(確保墊片在瀏覽器全局環(huán)境中)
其他方法:你可以使用qs庫來格式化數(shù)據(jù)。
var qs = require('qs'); axios.post('/foo', qs.stringify({'bar':123}));
Node.js
在nodejs中,你可以如下使用querystring:
var querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({foo:'bar'}));
你同樣可以使用qs庫。
promises
axios 基于原生的ES6 Promise 實(shí)現(xiàn)。如果環(huán)境不支持請使用墊片.
TypeScript
axios 包含TypeScript定義
import axios from 'axios' axios.get('/user?ID=12345')
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue前端el-input輸入限制輸入位數(shù)及輸入規(guī)則
這篇文章主要給大家介紹了關(guān)于vue前端el-input輸入限制輸入位數(shù)及輸入規(guī)則的相關(guān)資料,文中通過代碼介紹的介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用vue具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09Ant Design Vue resetFields表單重置不生效問題及解決
這篇文章主要介紹了Ant Design Vue resetFields 表單重置不生效問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06vue3.0 Reactive數(shù)據(jù)更新頁面沒有刷新的問題
這篇文章主要介紹了vue3.0 Reactive數(shù)據(jù)更新頁面沒有刷新的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04詳解element-ui 組件el-autocomplete使用踩坑記錄
最近使用了el-autocomplete組件,本文主要介紹了element-ui 組件el-autocomplete使用踩坑記錄,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03elementui時(shí)間/日期選擇器選擇禁用當(dāng)前之前(之后)時(shí)間代碼實(shí)例
當(dāng)我們在進(jìn)行網(wǎng)頁開發(fā)時(shí),通常需要用到一些日期組件來方便用戶選擇時(shí)間,其中element日期組件是一個(gè)非常好用的工具,這篇文章主要給大家介紹了關(guān)于elementui時(shí)間/日期選擇器選擇禁用當(dāng)前之前(之后)時(shí)間的相關(guān)資料,需要的朋友可以參考下2024-02-02vue.js給動(dòng)態(tài)綁定的radio列表做批量編輯的方法
下面小編就為大家分享一篇vue.js給動(dòng)態(tài)綁定的radio列表做批量編輯的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02vue安裝和使用scss及sass與scss的區(qū)別詳解
這篇文章主要介紹了vue安裝和使用教程,用了很久css預(yù)編譯器,但是一直不太清楚到底用的sass還是scss,直到有天被問住了有點(diǎn)尷尬,感興趣的朋友一起看看吧2018-10-10