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

