axios
axios 是一個(gè)基于 Promise 的 HTTP 客戶端,專門為瀏覽器和 node.js 服務(wù)
Vue 2.0 官方推薦使用 axios 來代替原來的 Vue request,所以這里介紹一下 axios 的功能和基本的使用方法,希望能夠?qū)Ω魑凰袔椭_^
功能
瀏覽器支持
axios 能夠支持 IE7 以上的 IE 版本,同時(shí)能夠支持大部分主流的瀏覽器,需要注意的是,你的瀏覽器需要支持 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); });
同時(shí)發(fā)送多個(gè)請求
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 }));
當(dāng)然,axios 的功能還包括 axios API、interceptor 等等,這里想要詳細(xì)了解的可以查看官方文檔:axios,后面陸續(xù)會(huì)介紹下 interceptor 的使用和各類參數(shù)的配置。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com