目录
1.axios
1.1官方文档
http://www.axios-js.com/zh-cn/docs/
1.2基本使用
1.2.1get请求
get请求需要添加params对象或者参数跟在请求地址后面
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
1.2.2post请求
post请求不需要加params
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
1.2.3执行多个并发请求
通常用在需要多个请求添加loading加载场景下使用
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) {
// 两个请求现在都执行完成
}));
1.2.4拦截器
在请求或响应被 then
或 catch
处理前拦截它们。
request拦截器针对用户请求进行拦截,通过config可以取到参数,对参数进行操作,比如对参数中的日期格式字符串转时间戳等等;
response 可以根据接口规范做错误拦截
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
1.3统一报错、未登录同意拦截、请求值、返回值同意处理示例
1.3.1main.js
import Vue from 'vue'
import router from "./router";
import axios from "axios";
import VueAxios from "vue-axios";
import App from './App.vue'
//设置axios 基础值
//根据前端跨域做调整,使用代理可以把api给替换为空
axios.defaults.baseURL ='/api';
//推荐是8秒
axios.defaults.timeout =8000;
Vue.use(VueAxios, axios);
//生产环境的提示
Vue.config.productionTip = false;
//接口规范如下
/*{
status:0,
data:[],
msg:""
}*/
//接口错误拦截
axios.interceptors.response.use(function (response) {
//取到返回的值
let res = response.data;
if (res.status == 0) {
//成功
res.data;
}else if(res.status == 10){
//未登录状态码,跳转登陆页面
window.location.href='/#/login';
}else{
alert(res.msg);
}
});
new Vue({
router: router,
render: h => h(App),
}).$mount('#app');