axios 獲取后臺數(shù)據(jù)

什么是axios

  • axios是一個獲取后臺數(shù)據(jù)的插件
  • 地址https://www.npmjs.com/package/axios
  • 使用 前提得安裝node.js
  • 頁面直接引用 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  • 下載 選中文件夾 shift+右鍵 調(diào)出命令窗口 輸入 npm i axios -g

axios的特性

1.可以從瀏覽器中創(chuàng)建XHR對象
2、可以從nodeJS中創(chuàng)建HTTP請求
3、支持Promise
4、可以攔截請求和響應
5、可以轉換請求數(shù)據(jù)和響應數(shù)據(jù)
6、可以取消請求
7、可以自動轉換JSON數(shù)據(jù)
8、客戶端支持防御XSRF

獲取數(shù)據(jù):
路徑為后臺數(shù)據(jù)接口
在用axios獲取后臺數(shù)據(jù)時,
  get  function(){
      var url = '路徑'
    axios.get(url,{params:參數(shù)}).then(function(儲存后臺數(shù)據(jù)的變量:A){    //then為成功后的回調(diào)
        對象名.渲染頁面的函數(shù)名(A.data)                     // data是在使用axios的時候,axios給數(shù)據(jù)添加了一個data來封裝獲得的數(shù)據(jù),
    }).catchcatch(function (用來儲存錯誤信息的變量:error){ // 捕捉錯誤
      alert(error)                                        // 請求失敗之后,執(zhí)行這個函數(shù)
    })
    }
  • axios get 方法
    僅僅請求后臺數(shù)據(jù)
axios.get('index.php')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

帶參數(shù)請求后臺數(shù)據(jù)

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

當然,也可以把參數(shù)數(shù)據(jù)直接寫到URL中

// 為給定 ID 的 user 創(chuàng)建請求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • aixos post方法
    一般來說,post請求更多的是要提交數(shù)據(jù),params屬性里的數(shù)據(jù)會出現(xiàn)在請求主體中。
    [注意]如果是axios.create()方法中的params屬性,則其里面的數(shù)據(jù)會出現(xiàn)在URL參數(shù)中。
    但實際上,post方法不需要使用params屬性,它的第二個參數(shù)就是要發(fā)送的數(shù)據(jù)。
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

多并發(fā)請求,一次性發(fā)幾個請求

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) {
    // acct為第一個請求的結果,perms為第二個請求的結果
  }));
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容