request.js 2.7 KB
import { pro_http } from '@/utils/baseUrl.js'
// 此vm参数为页面的实例,可以通过它引用vuex中的变量
module.exports = (vm) => {
    // 初始化请求配置
    uni.$u.http.setConfig((config) => {
        /* config 为默认全局配置*/
        config.baseURL = pro_http /* 根域名 */
        return config
    })
	
	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	  // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
		uni.showLoading({title: '玩命加载中...'})
	    config.data = config.data || {}
		// 根据custom参数中配置的是否需要token,添加对应的请求头
		if(config?.custom?.auth) {
			// 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
			config.header.Authorization = vm.$store.state.user.token
		}
	    return config 
	}, config => { // 可使用async await 做异步操作
	    return Promise.reject(config)
	})
	
	// 当前是否显示modal
	let loginModal = false
	
	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
		const data = response.data
		uni.hideLoading()
		// 自定义参数
		const custom = response.config?.custom
		if (data.code !== 200) { 
			// 判断是否需要登录
			if (data.code === 401) {
			  // 401也有可能是后端登录态到期, 所以要清空本地的登录状态
			  // vm.$store.dispatch('Logout')
			
			  // 防止重复弹窗
			  if (!loginModal) {
			    loginModal = true
			    // 弹窗告诉用户去登录
			    uni.showModal({
			      title: '温馨提示',
			      content: '此时此刻需要您登录喔~',
			      // showCancel: false,
			      confirmText: "去登录",
			      cancelText: "再逛会",
			      success: res => {
			        if (res.confirm) {
			          uni.navigateTo({
			            url: "/pages/login/index"
			          })
			        }
			        loginModal = false
			      }
			    })
			  }
			  // 返回错误的结果(catch接受数据)
			  return Promise.reject({
			    statusCode: 0,
			    errMsg: data.msg,
			    result: data
			  })
			}
			// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
			if (custom.toast !== false) {
				uni.$u.toast(data.msg)
			}
			// 如果需要catch返回,则进行reject
			if (custom?.catch) {
				return Promise.reject(data)
			} else {
				// 否则返回一个pending中的promise,请求不会进入catch中
				return new Promise(() => { })
			}
		}
		return data.data === undefined ? data : data.data
	}, (response) => { 
		// 对响应错误做点什么 (statusCode !== 200)
		return Promise.reject(response)
	})
}