Files
taimed-international-app/api/interceptors/response.ts

81 lines
2.7 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;
if (typeof httpData === 'string') {
try {
httpData = JSON.parse(httpData);
} catch (e) {
// 无法解析仍然返回原始 body
}
}
// 规范化 message 字段
const message = (httpData as IApiResponse).msg || (httpData as IApiResponse).message || (httpData as IApiResponse).errMsg || '';
const code = (httpData as IApiResponse).code;
// 成功判断
const successFlag = (httpData as IApiResponse).success === true || code === 0;
if (successFlag) {
// 返回原始 httpData
// 实际数据每个接口不同,调用者需根据实际情况取 .data 字段
return Promise.resolve(httpData);
}
// 登录失效或需要强制登录的一些 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 === 1100 || 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 });
}