generated from ccsens_fe/uni-vue3-template
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.
54 lines
1.5 KiB
54 lines
1.5 KiB
const WHITE_LIST = ['/pad/login']
|
|
|
|
import { useUserStoreWidthOut } from '@/store/modules/user'
|
|
|
|
const userStore = useUserStoreWidthOut()
|
|
|
|
export function setupHttp() {
|
|
uni.$u.http.setConfig({
|
|
loadingText: '努力加载中~',
|
|
loadingTime: 800,
|
|
header: {
|
|
'Content-Type': 'application/json;charset=utf-8',
|
|
'Access-Control-Allow-Origin': '*',
|
|
},
|
|
})
|
|
|
|
// 请求拦截,配置Token等参数
|
|
uni.$u.http.interceptor.request = config => {
|
|
// 可以对某个url进行特别处理,此url参数为this.$u.get(url)中的url值
|
|
// 最后需要将config进行return
|
|
if (!WHITE_LIST.includes(config.url)) {
|
|
// 不在 白名单里的请求 加token
|
|
config.header.Authorization = `Bearer ${userStore.token}`
|
|
}
|
|
|
|
uni.$u.count = 0
|
|
return config
|
|
// 如果return一个false值,则会取消本次请求
|
|
// if(config.url == '/user/rest') return false; // 取消某次请求
|
|
}
|
|
|
|
// 响应拦截,判断状态码是否通过
|
|
uni.$u.http.interceptor.response = res => {
|
|
if (!res) return Promise.reject('res is null')
|
|
const { code, msg, data } = res
|
|
|
|
if (code === 200) {
|
|
return Promise.resolve(data)
|
|
} else if (code === 401) {
|
|
uni.$u.api
|
|
.login()
|
|
.then(() => {
|
|
// TODO: 登录成功后重发请求
|
|
})
|
|
.catch((error: any) => {
|
|
uni.$u.alertError(error)
|
|
return Promise.reject('登录过期, 且自动登录失败')
|
|
})
|
|
} else {
|
|
uni.$u.toast(msg || '请求发生错误')
|
|
return Promise.reject(msg)
|
|
}
|
|
}
|
|
}
|
|
|