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:

$ npm install axios

使用 bower:

$ bower install axios

使用 CDN:

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

案例

  • 執(zhí)行 GET 請(qǐng)求
// 為給定 ID 的 user 創(chuàng)建請(qǐng)求
axios.get('/user?ID=12345')
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });


// 上面的請(qǐng)求也可以這樣做
axios.get('/user', {
        params: {
            ID: 12345
        }
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
  • 執(zhí)行 POST 請(qǐng)求
axios.post('/user', {
        firstname: 'Fred',
        lastName: 'Flintstone'
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
  • 執(zhí)行多個(gè)并發(fā)請(qǐng)求
function getUserAccount () {
    return axios.get('/user/12345');
}


function getUserPermissions () {
    return axios.get('/user/12345/permissions');
}


axios.all([getUserAccount(), getUserPermission()])
    .then(axios.spread(function (acct, perms) {
        // 兩個(gè)請(qǐng)求都執(zhí)行完成
    }));


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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)