1. 程式人生 > >axios簡單理解

axios簡單理解

發起一個GET請求

  • 直接使用axios('/user')方法,axios()方法預設為GET方式
axios(/user/12345);
  • 使用axios.get()方法,引數直接寫以?key=value的形式,多個使用?key1=value1&key2=value2
axios.get('/user?key=value')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 使用axios.get()方法,使用params
    物件來傳遞引數
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 使用配置式
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response)
{ response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) });

發起一個POST請求

  • 使用axios().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(axios.spread(function (acct, perms) {
    // 兩個請求都已完成
  }));
  • 使用配置式
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

參考連結:axios