axios 是一个基于 Promise 的 HTTP 客户端,专门为浏览器和 node.js 服务vue
Vue 2.0 官方推荐使用 axios 来代替原来的 Vue request,因此这里介绍一下 axios 的功能和基本的使用方法,但愿可以对各位全部帮助。^_^node
axios 可以支持 IE7 以上的 IE 版本,同时可以支持大部分主流的浏览器,须要注意的是,你的浏览器须要支持 Promise,才可以使用 axios。因此比较好的作法是先安装 polyfill,而后再使用 axios。ios
Using npm:npm
$ npm install axios
axios
Using bower:浏览器
$ bower install axios
markdown
Using cdn:post
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
lua
这里以 Vue 为例:在 NPM 中安装 axios 以后,须要在 main.js 文件中引用 packagespa
import axios from 'axios'
而后全局绑定
Vue.prototype.$http = axios
而后能够在 .vue 文件中使用 $http
来代替 axios
// 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); });
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 的使用和各种参数的配置。