axios
axios 是一個基于 Promise 的 HTTP 客戶端,專門為瀏覽器和 node.js 服務
Vue 2.0 官方推薦使用 axios 來代替原來的 Vue request,所以這里介紹一下 axios 的功能和基本的使用方法,希望能夠對各位所有幫助。^_^
功能
瀏覽器支持
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 的使用和各類參數的配置。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com