熟练使用 - axios

111 阅读1分钟
.then(res=>{},err=>{})//then的第二个参等同下面的catch抛错
==
.catch(err=>{ throw new Error(err) })

执行 GET 请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {//普通函数形式
    console.log(response);
  })
  .catch((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: 'Fred',
    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([getUserAccount(), getUserPermissions()])
  .then(res) {
console.log(res[0])
console.log(res[1])
    // 两个请求现在都执行完成
  }));

​