xinli/xinlidsj/utils/request.js
Lilixu007 b127837423 页面样式调整
AI语音的还未更改
2026-02-26 15:21:08 +08:00

77 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { getBaseUrl } from './config'
import { getToken, clearToken } from './auth'
// 用于存储认证失败的回调
let authFailureCallback = null
// 设置认证失败的回调函数
export function setAuthFailureCallback(callback) {
authFailureCallback = callback
}
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)
}
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()
}
}
resolve(res)
},
fail: (err) => {
console.error('请求失败:', err)
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)
}
})
})
}