標籤:客戶 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)