vue axios中文文档(一)

特色
浏览器端发起XMLHttpRequests请求
node端发起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>

示例
发起一个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({
  method:'get',
  url:'http://bit.ly/2mTM3Ny',
  responseType:'stream'
})
  .then(function(response){
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  })
axios(url[,config])

//发起一个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中指定。

猜你喜欢

转载自blog.csdn.net/a3060858469/article/details/80718430