完善登录与状态回显处理
This commit is contained in:
@@ -123,6 +123,82 @@ export async function call<R = undefined>(endpoint: string, data: unknown): Prom
|
||||
}
|
||||
}
|
||||
|
||||
// 使用用户令牌的API调用函数
|
||||
export async function callWithUserToken<R = undefined>(
|
||||
endpoint: string,
|
||||
data: unknown,
|
||||
userToken: string,
|
||||
onTokenExpired?: () => void
|
||||
): Promise<ApiResponse<R>> {
|
||||
try {
|
||||
// 发送请求
|
||||
const requestOptions = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${userToken}`,
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
}
|
||||
|
||||
const response = await fetch(`http://${API_BASE_URL}${endpoint}`, requestOptions)
|
||||
|
||||
// 如果返回401未授权,可能是用户令牌过期
|
||||
if (response.status === 401) {
|
||||
// 通知调用者令牌已过期,需要刷新或重新登录
|
||||
if (onTokenExpired) {
|
||||
onTokenExpired()
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: response.status,
|
||||
message: '用户会话已过期,请重新登录',
|
||||
}
|
||||
}
|
||||
|
||||
// 解析响应数据
|
||||
const type = response.headers.get('Content-Type') ?? 'text/plain'
|
||||
if (type.indexOf('application/json') !== -1) {
|
||||
const json = await response.json()
|
||||
if (!response.ok) {
|
||||
console.log('响应不成功', `status=${response.status}`, json)
|
||||
return {
|
||||
success: false,
|
||||
status: response.status,
|
||||
message: json.message || '请求失败',
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
data: json,
|
||||
}
|
||||
}
|
||||
else if (type.indexOf('text/plain') !== -1) {
|
||||
const text = await response.text()
|
||||
if (!response.ok) {
|
||||
console.log('响应不成功', `status=${response.status}`, text)
|
||||
return {
|
||||
success: false,
|
||||
status: response.status,
|
||||
message: text || '请求失败',
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
data: undefined as unknown as R,
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Error(`无法解析响应数据,未处理的 Content-Type: ${type}`)
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error('API call with user token failed:', e)
|
||||
throw new Error('服务调用失败', {cause: e})
|
||||
}
|
||||
}
|
||||
|
||||
// 统一的API响应类型
|
||||
export type ApiResponse<T = undefined> = {
|
||||
success: false
|
||||
|
||||
Reference in New Issue
Block a user