axios 全攻略之基本介紹與使用(GET 與 POST)

來源:互聯網
上載者:User

標籤:客戶   content   2.0   .com   user   rms   AC   unp   tst   

axios

axios 是一個基於 Promise 的 HTTP 用戶端,專門為瀏覽器和 node.js 服務

Vue 2.0 官方推薦使用 axios 來代替原來的 Vue request,所以這裡介紹一下 axios 的功能和基本的使用方法,希望能夠對各位所有協助。^_^

功能
  • 在瀏覽器中發送 XMLHttpRequests 請求
  • 在 node.js 中發送 http 請求
  • 支援 Promise API
  • 攔截請求和響應
  • 轉換請求和響應資料
  • 取消請求
  • 自動轉換 JSON 資料格式
  • 用戶端支援防範 XSRF 攻擊
瀏覽器支援

axios 能夠支援 IE7 以上的 IE 版本,同時能夠支援大部分主流的瀏覽器,需要注意的是,你的瀏覽器需要支援 Promise,才能夠使用 axios。所以比較好的做法是先安裝 polyfill,然後再使用 axios。

安裝

Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using cdn:

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

使用

這裡以 Vue 為例:在 NPM 中安裝 axios 之後,需要在 main.js 檔案中引用 package

import axios from ‘axios‘

然後全域綁定

Vue.prototype.$http = axios

然後可以在 .vue 檔案中使用 $http 來代替 axios

GET
// Make a request for a user with a given ID axios.get(‘/user?ID=12345‘)  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  });// Optionally the request above could also be done as axios.get(‘/user‘, {    params: {      ID: 12345    }  })  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  }); 

 

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) {    // Both requests are now complete   }));

 

當然,axios 的功能還包括 axios API、interceptor 等等,這裡想要詳細瞭解的可以查看官方文檔:axios,後面陸續會介紹下 interceptor 的使用和各類參數的配置。

著作權聲明:本作品採用知識共用署名-非商業性使用-禁止演繹 3.0 未語言版本許可協議進行許可。 77650059

axios 全攻略之基本介紹與使用(GET 與 POST)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.