Axios起步

2022-02-28 11:40 更新

什么是Axios?

Axios 是一個(gè)基于 promise 的 HTTP 庫(kù),可以用在瀏覽器和 node.js 中。


特性

  • 從瀏覽器中創(chuàng)建 XMLHttpRequests
  • 從 node.js 創(chuàng)建 http 請(qǐng)求
  • 支持 Promise API
  • 攔截請(qǐng)求和響應(yīng)
  • 轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
  • 取消請(qǐng)求
  • 自動(dòng)轉(zhuǎn)換 JSON 數(shù)據(jù)
  • 客戶端支持防御 XSRF

安裝

使用 npm:

  1. $ npm install axios

使用 bower:

  1. $ bower install axios

使用 CDN:

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

案例

  • 執(zhí)行 GET 請(qǐng)求
  1. // 為給定 ID 的 user 創(chuàng)建請(qǐng)求
  2. axios.get('/user?ID=12345')
  3.     .then(function (response) {
  4.         console.log(response);
  5.     })
  6.     .catch(function (error) {
  7.         console.log(error);
  8.     });
  9. // 上面的請(qǐng)求也可以這樣做
  10. axios.get('/user', {
  11.         params: {
  12.             ID: 12345
  13.         }
  14.     })
  15.     .then(function (response) {
  16.         console.log(response);
  17.     })
  18.     .catch(function (error) {
  19.         console.log(error);
  20.     });
  • 執(zhí)行 POST 請(qǐng)求
  1. axios.post('/user', {
  2.         firstname: 'Fred',
  3.         lastName: 'Flintstone'
  4.     })
  5.     .then(function (response) {
  6.         console.log(response);
  7.     })
  8.     .catch(function (error) {
  9.         console.log(error);
  10.     });
  • 執(zhí)行多個(gè)并發(fā)請(qǐng)求
  1. function getUserAccount () {
  2.     return axios.get('/user/12345');
  3. }
  4. function getUserPermissions () {
  5.     return axios.get('/user/12345/permissions');
  6. }
  7. axios.all([getUserAccount(), getUserPermission()])
  8.     .then(axios.spread(function (acct, perms) {
  9.         // 兩個(gè)請(qǐng)求都執(zhí)行完成
  10.     }));


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)