interceptors.js 2.7 KB
import { http, toast} from '@/uni_modules/uview-plus'
import useUserStore from '@/store/modules/user.js'
const requestInterceptors=(vm)=>{
	/**
	 * 请求拦截
	 * @param {Object} http
	 */
	http.interceptors.request.use((config) => { // 可使用async await 做异步操作
		// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
		config.data = config.data || {}
		uni.showLoading({title: '加载中'})
		// 根据custom参数中配置的是否需要token,添加对应的请求头
		if(config?.custom?.auth) {
			const userStore = useUserStore()
			// 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
			config.header.Authorization = userStore.token
		}
		// console.log(config)
		return config
	}, (config) => // 可使用async await 做异步操作
		Promise.reject(config))
}
// 当前是否显示modal
let loginModal = false
	
const responseInterceptors=(vm)=>{
	/**
	 * 响应拦截
	 * @param {Object} http 
	 */
	http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
		const data = response.data
		uni.hideLoading();
		if(data.code === 401 ) {
			// 判断是否为用户
			const userStore = useUserStore()
			if(userStore.roleGroup === '普通角色'){
				uni.login({
				  success: async (loginRes) => {
						await userStore.login({code: loginRes.code, type: 0})
						uni.switchTab({
							url: '/pages/index/index'
						})
				  }
				});
			}else {
				// 防止重复弹窗
				if (!loginModal) {
					loginModal = true
					// 弹窗告诉用户去登录
					uni.showModal({
						title: '温馨提示',
						content: '你的身份信息已过期,需要重新登录~',
						// showCancel: false,
						confirmText: "前往登录",
						cancelText: "暂不登录",
						success: res => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/login'
								})
							}
							if (res.cancel) {
								
							}
							loginModal = false
						}
					})
				}
			}
		}
		// 自定义参数
		const custom = response.config?.custom
		if (data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
			// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
			if (custom.toast !== false) {
				toast(data.msg)
			}
			// 如果需要catch返回,则进行reject
			if (custom?.catch) {
				return Promise.reject(data)
			} else {
				// 否则返回一个pending中的promise
				return new Promise(() => { })
			}
		}
		return data || {}
	}, (response) => { /*  对响应错误做点什么 (statusCode !== 200)*/
	let { code, msg } = response
		return Promise.reject(response)
	})
}


export {
	requestInterceptors,
	responseInterceptors
}