xinli/xinlidsj/utils/request.js

77 lines
1.9 KiB
JavaScript
Raw Normal View History

2026-02-24 16:49:05 +08:00
import { getBaseUrl } from './config'
import { getToken, clearToken } from './auth'
// 用于存储认证失败的回调
let authFailureCallback = null
// 设置认证失败的回调函数
export function setAuthFailureCallback(callback) {
authFailureCallback = callback
}
2026-02-24 16:49:05 +08:00
export function request(options) {
const baseUrl = getBaseUrl()
const token = getToken()
const headers = Object.assign({}, options.header || {})
if (token) {
const normalized = token.startsWith('Bearer ') ? token : ('Bearer ' + token)
headers['Authorization'] = normalized
console.log('请求URL:', baseUrl + options.url)
console.log('Authorization头:', normalized.substring(0, 50) + '...')
} else {
console.warn('请求时没有token:', baseUrl + options.url)
2026-02-24 16:49:05 +08:00
}
return new Promise((resolve, reject) => {
uni.request({
...options,
url: baseUrl + options.url,
header: headers,
success: (res) => {
const data = res.data
// 统一处理认证失败
if (data && (data.code === 401 || data.code === 403)) {
console.error('认证失败清除token并显示登录弹窗:', data.msg)
// 清除过期的token
clearToken()
// 调用认证失败回调(显示登录弹窗)
if (authFailureCallback) {
authFailureCallback()
}
}
2026-02-24 16:49:05 +08:00
resolve(res)
},
fail: (err) => {
console.error('请求失败:', err)
2026-02-24 16:49:05 +08:00
reject(err)
}
})
})
}
export function uploadFile({ url, filePath, name = 'file', formData = {} }) {
const baseUrl = getBaseUrl()
const token = getToken()
const header = {}
if (token) {
const normalized = token.startsWith('Bearer ') ? token : ('Bearer ' + token)
header['Authorization'] = normalized
}
return new Promise((resolve, reject) => {
uni.uploadFile({
url: baseUrl + url,
filePath,
name,
formData,
header,
success: (res) => {
resolve(res)
},
fail: (err) => {
reject(err)
}
})
})
}