Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
安装
使用npm安装
使用 bower安装
使用 cdn:
1
| <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
|
例子:
vue中全局使用
1.结合 vue-axios使用
看了vue-axios的源码,它是按照vue插件的方式去写的。那么结合vue-axios,就可以去使用vue.use方法了
首先在主入口文件main.js中引用:
1 2 3 4
| import axios from 'axios' import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);
|
之后就可以使用了,在组件文件中的methods里去使用了:
1 2 3 4 5 6 7
| getNewsList(){ this.axios.get('api/getNewsList').then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); }) }
|
2.axios 改写为 Vue 的原型属性
首先在主入口文件main.js中引用,之后挂在vue的原型链上:
1 2
| import axios from 'axios' Vue.prototype.$ajax= axios
|
在组件中使用:
1 2 3 4 5 6
| this.$ajax.get('api/getNewsList') .then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); })
|
局部使用
直接引入
1
| import axios from 'axios'
|
然后就可以直接用了
常用的配置项初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| axios.defaults.baseURL = 'https://127.0.0.1:9999'; axios.defaults.withCredentials =true; axios.defaults.header['Content-Type'] = 'application/x-www-form-urlencoded'; axios.defaults.headers.common["token"] = token;
axios.defaults.transformRequest = function (data) { if (data) return data; let result = ``; for (let attr in data) {2 if(!data.hasOwnProperty(attr)) break; result += `&${attr}=${data[attr]}`; } return result.substring(1); };
axios.interceptor.response.use(function onFultfilled(response) { return response.data; }, function onRejected(reason) { return Promise.reject(reason); });
axios.dafaults.validateStatus = function (status) { return /^(2\3)\d{2}$/.test(status); }
|
使用方式示例
1.执行get数据请求
1 2 3 4 5 6 7 8 9 10 11
| axios.get('url',{ params:{ id:'接口配置参数(相当于url?id=xxxx)', }, }) .then((res)=>{ console.log(res); }) .catch((error)=>{ console.log(error) })
|
2.执行post数据发送
1 2 3 4 5 6 7 8 9 10 11
| const data = { name:'张三', age:23 } axios.post('url',data) .then((res)=>{ console.log(res); }) .catch((error)=>{ console.log(error) })
|
3.执行delete 数据发送
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| axios.delete('demo/url', { data: { id: 123, name: 'Henry', }, timeout: 1000, })
axios.delete('demo/url', { params: { id: 123, name: 'Henry', }, timeout: 1000 })
|
4.执行put 数据发送
1 2 3 4 5 6
| axios.put('demo/url', { id: 123, name: 'Henry', sex: 1, phone: 13333333 })
|
5.携带请求头
axios设置请求头中的Authorization信息:
GET请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| this.$axios.get('/url', { headers: { 'Authorization': 'Bearer '+localStorage.getItem('token'), 'token': ' ' ... }, params: { param1: string, param2: string }, ... } ) .then(res => fn) .catch(err => fn)
|