一。安装

1.1、利用 npm 安装

npm install axios --save

1.2、利用 bower 安装

bower install axios --save

1.3、直接利用 cdn 引入

<script src="https:// unpkg.com/axios/dist/axios.min.js"></script>

二。例子

2.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.2、发送一个 post 请求

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

2.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

3.1、axios 可以通过配置 (config) 来发请求

3.1.1、axios(config)

// 发送一个`POST`请求
axios({
  method:"POST",
  url:'/user/12345',
  data:{
    firstName:"Fred",
    lastName:"Flintstone"
  }
});

3.1.2、axios(url [,config])

// 发送一个`GET`请求(默认的请求方式)
axios('/user/12345');