http.interceptor.js 1.39 KB
import config from '@/config.js'
import common from '@/utils/wxApplet/common.js'

/**
 * http拦截器
 */
const install = (Vue, vm) => {
	// 自定义配置参数
	Vue.prototype.$u.http.setConfig({
		baseUrl: config.HTTP_REQUEST_URL,
		loadingText: '努力加载中~',
		loadingTime: 800,
		// ......
	});

	// 请求拦截
	Vue.prototype.$u.http.interceptor.request = (configs) => {
		configs.header[config.TOKEN_NAME] = vm.$store.state.vuex_token ? vm.$store.state.vuex_token : "";
		return configs;
	}

	// 响应拦截
	Vue.prototype.$u.http.interceptor.response = (res) => {
		// res为服务端返回值,有code、message、data等字段
		if (res.code == 10000) {
			return res.data;
		}
		// else if (res.code == -101) {
		// 	// Token快过期,替换新的token
		// 	vm.$u.vuex('vuex_token', res.data.token);
		// 	// 无痛刷新token
		// 	return vm.$u.post(Vue.prototype.$u.http.options.url).then(result => {
		// 		return result;
		// 	})
		// } 
		else if (res.code == 10006 || res.code == 10007) {
			// Token已过期|加入黑名单|Token校验失败,则需重新进入登录页登录
			common.logout();
			uni.reLaunch({
				url: '/pages/common/login'
			});
			return false;
		} else {
			// 如果返回false,则会调用Promise的reject回调
			if (res.message) {
				vm.$u.toast(res.message)
			} else {
				vm.$u.toast(res)
			}
			return false;
		}
	}

}

export default {
	install
}