axios
安装 axios 依赖
1
| npm install axios --save
|
导入
1
| import axios from 'axios'
|
简单使用
1 2 3 4 5 6 7 8 9 10 11
| axios({ url: 'http://123.207.32.32:8000/home/multidata', params: { type: 'aaa', name: 'bbb' }, method: 'get' }).then(res => { console.log(res); })
|
发送并发请求
并发请求的结果是以一个数组的方式返回
1 2 3 4 5 6 7 8 9 10 11
| axios.all([axios({ url: 'http://123.207.32.32:8000/home/multidata' }), axios({ url: 'http://123.207.32.32:8000/home/data', params: { type: 'sell', page: 3 } })]).then(results => { console.log(results); })
|
将数组里的结果独立显示
1 2 3 4 5 6 7 8 9 10 11 12
| axios.all([axios({ url: 'http://123.207.32.32:8000/home/multidata' }), axios({ url: 'http://123.207.32.32:8000/home/data', params: { type: 'sell', page: 3 } })]).then(axios.spread((res1, res2) => { console.log(res1); console.log(res2); }))
|
axios全局配置
常见的配置信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| axios.defaults.baseURL = 'http://123.207.32.32:8000' axios.defaults.timeout = 5000
axios.all([axios({ url: '/home/multidata' }), axios({ url: '/home/data', params: { type: 'sell', page: 3 } })]).then(axios.spread((res1, res2) => { console.log(res1); console.log(res2); }))
|
axios的实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const instance1 = axios.create({ baseURL: 'http://123.207.32.32:8000', timeout: 5000 })
const instance2 = axios.create({ baseURL: 'https://httpbin.org/get', timeout: 5000 })
instance1({ url: '/home/multidata' }).then(res => { console.log(res); })
instance2({ url: '' }).then(res => { console.log(res); })
|
封装axios
为什么需要封装?
为了防止以后如果你使用的这个框架,或者插件不再更新或者维护,能够以最简便的方式去替换掉
创建一个 network 文件夹,下创建一个 request.js 文件
1 2 3 4 5 6 7 8 9 10 11
| import axios from 'axios' export function request(config) { const instance = axios.create({ baseURL: 'http://123.207.32.32:8000', timeout: 5000 })
return instance(config) }
|
模拟使用
1 2 3 4 5 6 7 8
| import {request} from './network/request' request({ url: '/home/multidata' }).then(res => { console.log(res); }).catch(err => { console.log(err); })
|
拦截器
request.js
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 31
| export function request(config) { const instance = axios.create({ baseURL: 'http://123.207.32.32:8000', timeout: 5000 })
instance.interceptors.request.use(config => { console.log(config); return config }, error => { console.log(error); })
instance.interceptors.response.use(res => { console.log(res); return res.data }, error => { console.log(error);
}) return instance(config) }
|
main.js
1 2 3 4 5 6 7 8
| import {request} from './network/request' request({ url: '/home/multidata' }).then(res => { console.log(res); }).catch(err => { console.log(err); })
|