import config from "@/config";
|
// 此vm参数为页面的实例,可以通过它引用vuex中的变量
|
module.exports = (vm) => {
|
// 初始化请求配置
|
uni.$u.http.setConfig((httpRequestConfig) => {
|
/* config 为默认全局配置*/
|
httpRequestConfig.baseURL = config.host; /* 根域名 */
|
httpRequestConfig.dataType = 'json';
|
httpRequestConfig.header ={'Content-type': 'application/json; charset=UTF-8'}
|
return httpRequestConfig
|
})
|
|
// 请求拦截
|
uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
|
// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
|
config.data = config.data || {}
|
// 根据custom参数中配置的是否需要token,添加对应的请求头
|
// 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
|
config.header["Authorization"] = vm.sso_user_token
|
return config
|
}, config => { // 可使用async await 做异步操作
|
return Promise.reject(config)
|
})
|
|
// 响应拦截
|
uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
|
const res = response.data;
|
if(res.code === 200) {
|
return res.data?res.data:res;
|
} else if (res.code === 401){
|
vm.$u.toast("登录失效,请重新登录");
|
setTimeout(() => {
|
vm.$u.route('/pages/login/index')
|
}, 1500)
|
return false;
|
}else {
|
vm.$u.toast(res.msg);
|
return Promise.reject(response);
|
};
|
}, (response) => {
|
// 对响应错误做点什么 (statusCode !== 200)
|
return Promise.reject(response)
|
})
|
}
|