You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.9 KiB
55 lines
1.9 KiB
const install = (Vue, vm) => {
|
|
Vue.prototype.$u.http.setConfig({
|
|
baseUrl: '',
|
|
showLoading: true, // 是否显示请求中的loading
|
|
loadingText: '玩命加载中...',
|
|
loadingTime: 800,
|
|
loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
|
|
// 配置请求头信息
|
|
header: { 'content-type': 'application/json;charset=UTF-8' },
|
|
});
|
|
|
|
// 请求拦截部分,如配置,每次请求前都会执行
|
|
Vue.prototype.$u.http.interceptor.request = config => {
|
|
// TODO: 如果在白名单里 则不需要加token
|
|
|
|
if (vm.$store.state.user.token) {
|
|
config.header.Authorization = `Bearer ${vm.$store.state.user.token}`;
|
|
}
|
|
|
|
return config;
|
|
};
|
|
|
|
// 响应拦截,如配置,每次请求结束都会执行本方法
|
|
Vue.prototype.$u.http.interceptor.response = res => {
|
|
if (res.code === 200) {
|
|
// res为服务端返回值,可能有code,result等字段
|
|
// 这里对res.result进行返回,将会在this.$u.post(url).then(res => {})的then回调中的res的到
|
|
// 如果配置了originalData为true,请留意这里的返回值
|
|
return res.data;
|
|
} else if (res.code === 401) {
|
|
// 假设201为token失效,这里跳转登录
|
|
vm.$u.toast('验证失败,请重新登录');
|
|
setTimeout(() => {
|
|
// 此为uView的方法,详见路由相关文档
|
|
vm.$u.route('/pages/user/login');
|
|
}, 1500);
|
|
return false;
|
|
} else {
|
|
// 如果返回false,则会调用Promise的reject回调,
|
|
// 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值
|
|
return false;
|
|
}
|
|
};
|
|
|
|
Vue.prototype.$u.post = (url, param = {}, header = {}) => {
|
|
return Vue.prototype.$u.http.request({
|
|
url,
|
|
method: 'POST',
|
|
header,
|
|
data: { param },
|
|
});
|
|
};
|
|
};
|
|
|
|
export default { install };
|
|
|