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.
 
 
 
 
 

69 lines
2.1 KiB

import { useUserStore } from "../stores/modules/userInfo";
const baseURL = "https://hwjb.homilychart.com/testApi"
const httpInterceptor = {
// 拦截前触发
invoke(options) {
// 1.非http
if (!options.url.startsWith('http')) {
options.url = baseURL + options.url
}
// 2.请求超时,默认60s
options.timeout = 60000
console.log(options)
//3 添加小程序端请求头
options.header = {
...options.header,
'source-client': 'miniapp'
}
//4 添加token
const memberStore = useUserStore()
const token = memberStore.userInfo?.token
if (token) {
options.header.Authorization = token
}
return options
}
}
// 添加拦截器
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
// 添加请求函数
export const http = (options) => {
return new Promise((resolve, reject) => {
uni.request({
...options,
// 1.请求成功
success: (result) => {
if (result.statusCode >= 200 && result.statusCode < 300) {
resolve(result.data)
} else if (result.statusCode === 401) {
// 清除登录信息
const memberStore = useUserStore()
memberStore.clearUserInfo()
// 提示用户重新登录
uni.navigateTo({
url: '/pages/login/login'
})
reject(result)
} else {
uni.showToast({
title: (result.data).msg || '请求失败',
icon: 'none'
})
reject(result)
}
},
// 2.请求失败
fail: (err) => {
reject(err)
uni.showToast({
title: '网络错误',
icon: 'none'
})
}
})
})
}