详解axios 全攻略之基本介绍与使用(GET 与 POST)
axios
axios是一个基于Promise的HTTP客户端,专门为浏览器和node.js服务
Vue2.0官方推荐使用axios来代替原来的Vuerequest,所以这里介绍一下axios的功能和基本的使用方法,希望能够对各位所有帮助。^_^
功能
- 在浏览器中发送XMLHttpRequests请求
- 在node.js中发送http请求
- 支持PromiseAPI
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据格式
- 客户端支持防范XSRF攻击
浏览器支持
axios能够支持IE7以上的IE版本,同时能够支持大部分主流的浏览器,需要注意的是,你的浏览器需要支持Promise,才能够使用axios。所以比较好的做法是先安装polyfill,然后再使用axios。
安装
Usingnpm:
$npminstallaxios
Usingbower:
$bowerinstallaxios
Usingcdn:
使用
这里以Vue为例:在NPM中安装axios之后,需要在main.js文件中引用package
importaxiosfrom'axios'
然后全局绑定
Vue.prototype.$http=axios
然后可以在.vue文件中使用$http来代替axios
GET
//MakearequestforauserwithagivenID
axios.get('/user?ID=12345')
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
//Optionallytherequestabovecouldalsobedoneas
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
POST
axios.post('/user',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
同时发送多个请求
functiongetUserAccount(){
returnaxios.get('/user/12345');
}
functiongetUserPermissions(){
returnaxios.get('/user/12345/permissions');
}
axios.all([getUserAccount(),getUserPermissions()])
.then(axios.spread(function(acct,perms){
//Bothrequestsarenowcomplete
}));
当然,axios的功能还包括axiosAPI、interceptor等等,这里想要详细了解的可以查看官方文档:axios,后面陆续会介绍下interceptor的使用和各类参数的配置。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。