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.

133 lines
3.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import {
ROOTPATH as baseUrl
} from "@/common/config.js"
// 这里的Vue为Vue对象(非创建出来的实例)vm为main.js中“Vue.use(httpInterceptor, app)”这一句的第二个参数,
// 为一个Vue的实例也即每个页面的"this"
// 如果需要了解这个install方法是什么请移步https://uviewui.com/components/vueUse.html
const install = (Vue, vm) => {
// 此为自定义配置参数,具体参数见上方说明
Vue.prototype.$u.http.setConfig({
baseUrl,
showLoading: false, // 是否显示请求中的loading
loadingMask: false, // 展示loading的时候是否给一个透明的蒙层防止触摸穿透
loadingText: '', // 请求loading中的文字提示
loadingTime: 800,
originalData: true, // 是否在拦截器中返回服务端的原始数据
// 设置自定义头部content-type
header: {
'content-type': 'application/json;charset=UTF-8'
}
});
// 请求拦截部分,如配置,每次请求前都会执行
Vue.prototype.$u.http.interceptor.request = (config) => {
console.log('config-http', config)
let mkwcancel_lifeData = uni.getStorageSync('mkwcancel_lifeData')
let vuex_token = mkwcancel_lifeData.vuex_token;
if (vuex_token || vm.vuex_token) {
config.header['Authorization'] = `Bearer ${vuex_token || vm.vuex_token}`;
}
return config;
}
// 响应拦截,如配置,每次请求结束都会执行本方法
Vue.prototype.$u.http.interceptor.response = (res) => {
console.log('res-http', res)
// 处理网络错误
if (res.statusCode !== 200) {
let errorMsg = '网络错误'
switch(res.statusCode) {
case 401:
errorMsg = '未授权,请重新登录'
handleAuthError()
break
case 403:
errorMsg = '禁止访问'
break
case 404:
errorMsg = '请求地址不存在'
break
case 500:
errorMsg = '服务器内部错误'
break
default:
errorMsg = `网络错误 ${res.statusCode}`
}
uni.showToast({
icon: "none",
title: errorMsg
})
return Promise.reject(res)
}
// 处理业务逻辑
if (res.data && res.data.hasOwnProperty("errcode")) {
if (res.data.errcode === 1000) {
// 成功
return res.data
} else if (res.data.errcode === 40001) {
// token失效或未认证
handleAuthError()
return Promise.reject(res.data)
} else {
// 其他业务错误
const errorMsg = res.data.msg || '请求失败'
uni.showToast({
icon: "none",
title: errorMsg
})
return Promise.reject(res.data)
}
} else if (res.data && res.data.access_token) {
// 特殊处理登录接口返回的access_token格式
return res.data
} else if (res.data) {
// 其他有数据的响应,直接返回
return res.data
} else {
// 响应格式错误
uni.showToast({
icon: "none",
title: '响应格式错误'
})
return Promise.reject(res)
}
}
// 处理认证错误的函数
function handleAuthError() {
// 清除本地存储的认证信息
uni.removeStorageSync('mkwcancel_lifeData')
// 清除vuex中的认证信息
if (vm && vm.$u && vm.$u.vuex) {
vm.$u.vuex('vuex_token', '')
vm.$u.vuex('vuex_user', {})
}
// 显示提示
uni.showModal({
title: '认证失效',
content: '登录状态已失效,请重新登录',
showCancel: false,
confirmText: '去登录',
success: function() {
// 跳转到登录页面
uni.reLaunch({
url: '/pages/login/index'
})
}
})
}
}
export default {
install
}