Files
taimed-international-app/api/interceptors/response.ts
fuchao 64abd3d4ab revert 33c22eaad9
revert 解决冲突
2025-11-27 15:38:24 +08:00

80 lines
2.9 KiB
TypeScript
Raw 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 type { IApiResponse } from '../types';
import { t } from '@/utils/i18n'
/**
* 响应拦截器:严格兼容原项目返回约定
*
* 原项目要点回顾:
* - 当 response.statusCode == 200 且 (body.success === true || body.code == 0) 时判定为成功;
* - 部分错误码("401", 1000,1001,1100,402 等)表示需要重新登录/清除状态并跳转;
* - 错误时会返回 Promise.reject({ statusCode: 0, errMsg: ... , data: body })
*
*/
function handleAuthExpired() {
// 清空本地登录信息
try {
uni.removeStorageSync('userInfo');
} catch (e) {}
// 跳转 login与原项目保持一致的路径
uni.showToast({ title: t('global.loginExpired'), icon: 'none' });
setTimeout(() => {
uni.reLaunch({ url: '/pages/login/login' });
}, 600);
}
export function responseInterceptor(res: UniApp.RequestSuccessCallbackResult) {
// 先处理非 200 的 http 状态
if (res.statusCode && res.statusCode !== 200) {
const msg = `${t('global.networkConnectionError')} (${res.statusCode})`;
setTimeout(() => {
uni.showToast({ title: msg, icon: 'none' });
}, 10);
return Promise.reject({ statusCode: res.statusCode, errMsg: msg, response: res });
}
// 可能为字符串,尝试解析(原项目也做了类似处理)
let httpData: IApiResponse | string = res.data as any;
if (typeof httpData === 'string') {
try {
httpData = JSON.parse(httpData);
} catch (e) {
// 无法解析仍然返回原始 body
}
}
// 规范化 message 字段
const message = (httpData as any).msg || (httpData as any).message || (httpData as any).errMsg || '';
// 成功判断:与原项目一致的条件
const successFlag = (httpData as any).success === true || (httpData as any).code === 0;
if (successFlag) {
// 返回原始 httpData与原项目 dataFactory 返回 Promise.resolve(httpData) 保持一致)
// 但大多数调用者更关心 data 字段,这里返回整个 httpData调用者可取 .data
return Promise.resolve(httpData);
}
// 登录失效或需要强制登录的一些 code与原项目一致
const code = (httpData as any).code;
if (code === '401' || code === 401) {
// 触发登出流程
handleAuthExpired();
return Promise.reject({ statusCode: 0, errMsg: t('global.loginExpired'), data: httpData });
}
// 原项目还将 1000,1001,1100,402 等视作需要强制登录
if (code === '1000' || code === '1001' || code === 1000 || code === 1001 || code === 1100 || code === '402' || code === 402) {
handleAuthExpired();
return Promise.reject({ statusCode: 0, errMsg: message || t('global.loginExpired'), data: httpData });
}
// 其他后端业务错误toast 并 reject
const errMsg = message || t('global.requestException');
if (errMsg) {
uni.showToast({ title: errMsg, icon: 'none' });
}
return Promise.reject({ statusCode: 0, errMsg, data: httpData });
}