Axios POST、GET、多併發請求

Axios是一個基於promise的HTTP庫,可以用在瀏覽器和node.js中。

  • 安裝
    • npm install axios --save
    • cnpm install axios --save
    • 使用CDN <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  • GET請求
axios.get('/getUserInfo?id=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// 可選地,上面的請求可以這樣做
axios.get('/getUserIngo', {
    params: {
      id: 1
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • POST請求
axios.post('/user', {
    firstName: 'newName',
    lastName: 'lastName'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 執行多個併發請求
function getUserAccount() {
  return axios.get('/getUserInfo/1');
}

function getUserPermissions() {
  return axios.get('/getUserInfo/1/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 兩個請求現在都執行完成
  }));

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章