配置utils/request
This commit is contained in:
parent
28cbac1be2
commit
a0d674b05a
|
|
@ -0,0 +1,77 @@
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化请求拦截器
|
||||||
|
* 使用 Pinia store 管理用户状态和 token
|
||||||
|
*/
|
||||||
|
export const Request = () => {
|
||||||
|
// 初始化请求配置
|
||||||
|
uni.$uv.http.setConfig((config) => {
|
||||||
|
/* config 为默认全局配置*/
|
||||||
|
config.baseURL = 'https://www.example.com'; /* 根域名 */
|
||||||
|
return config
|
||||||
|
})
|
||||||
|
|
||||||
|
// 请求拦截
|
||||||
|
uni.$uv.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
|
||||||
|
// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
|
||||||
|
config.data = config.data || {}
|
||||||
|
|
||||||
|
// 根据custom参数中配置的是否需要token,添加对应的请求头
|
||||||
|
if(config?.custom?.auth) {
|
||||||
|
// 使用 Pinia store 获取 token
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const token = userStore.getToken || userStore.token
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
config.header.token = token
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return config
|
||||||
|
}, config => { // 可使用async await 做异步操作
|
||||||
|
return Promise.reject(config)
|
||||||
|
})
|
||||||
|
|
||||||
|
// 响应拦截
|
||||||
|
uni.$uv.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
|
||||||
|
const data = response.data
|
||||||
|
|
||||||
|
// 自定义参数
|
||||||
|
const custom = response.config?.custom
|
||||||
|
|
||||||
|
// 处理 token 过期等情况(根据实际业务调整)
|
||||||
|
if (data.code === 401 || data.code === 403) {
|
||||||
|
// token 过期或无效,清除登录状态
|
||||||
|
const userStore = useUserStore()
|
||||||
|
userStore.logout()
|
||||||
|
|
||||||
|
// 跳转到登录页面(根据实际路由调整)
|
||||||
|
// uni.reLaunch({ url: '/pages/login/index' })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.code !== 200) {
|
||||||
|
// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
|
||||||
|
if (custom?.toast !== false) {
|
||||||
|
uni.$uv.toast(data.message || '请求失败')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果需要catch返回,则进行reject
|
||||||
|
if (custom?.catch) {
|
||||||
|
return Promise.reject(data)
|
||||||
|
} else {
|
||||||
|
// 否则返回一个pending中的promise,请求不会进入catch中
|
||||||
|
return new Promise(() => { })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data.data === undefined ? {} : data.data
|
||||||
|
}, (response) => {
|
||||||
|
// 对响应错误做点什么 (statusCode !== 200)
|
||||||
|
// 网络错误或服务器错误处理
|
||||||
|
if (response.statusCode === 401 || response.statusCode === 403) {
|
||||||
|
const userStore = useUserStore()
|
||||||
|
userStore.logout()
|
||||||
|
// uni.reLaunch({ url: '/pages/login/index' })
|
||||||
|
}
|
||||||
|
return Promise.reject(response)
|
||||||
|
})
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user