axios
基於http客戶端的promise,面向瀏覽器和nodejs
特色
瀏覽器端發起XMLHttpRequests請求
node端發起http請求
支持Promise API
監聽請求和返回
轉化請求和返回
取消請求
自動轉化json數據
客戶端支持抵禦
安裝
//使用npm:
$ npm i axiso
使用 bower
$ bower instal axios
//使用cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
示例
使用一個 GET
請求
//發起一個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)
});
發起一個 POST
請求
axios.post('/user',{
firstName:'friend',
lastName:'Flintstone'
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
發起一個多重併發請求
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)
//發起 POST請求
axios({
method:'post',
url:'/user/12345',
data:{
firstName:'Fred',
lastName:'Flintstone'
}
});
axios(url[,config])
//發起一個GET請求
axios('/user/12345/);
請求方法的重命名。
爲了方便,axios提供了所有請求方法的重命名支持
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
, method
,以及 data
特性不需要在config中設置。