axios介绍,为什么用axios?

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端。这就是为什么用这个。

一、安装

1、 利用npm安装npm install axios --save
2、 利用bower安装bower install axios --save
3、 直接利用cdn引入

二、使用

1、 发送一个GET请求

//通过给定的ID来发送请求
axios.get('/user?ID=12345')
  .then(function(response){
    console.log(response);
  })
  .catch(function(err){
    console.log(err);
  });
//以上请求也可以通过这种方式来发送
axios.get('/user',{
  params:{
    ID:12345
  }
})
.then(function(response){
  console.log(response);
})
.catch(function(err){
  console.log(err);
});

2、 发送一个POST请求

axios.post('/user',{
  firstName:'Fred',
  lastName:'Flintstone'
})
.then(function(res){
  console.log(res);
})
.catch(function(err){
  console.log(err);
});

3、 一次性并发多个请求

function getUserAccount(){
  return axios.get('/user/12345');
}
function getUserPermissions(){
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(),getUserPermissions()])
  .then(axios.spread(function(acct,perms){
    //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果
  }))

三、axios更多

更多当然是去看官方API咯,哈哈哈!!!

原文地址:https://www.cnblogs.com/junhey/p/7127058.html