BikeApp_demo/src/utils/api.ts

104 lines
2.7 KiB
TypeScript
Raw Normal View History

2024-12-17 16:39:34 +08:00
import axios from 'axios';
import { auth } from '../utils/auth';
// 全局方法
let showToast: (message: string) => void;
let globalLogout: (() => Promise<void>) | null = null;
export const setToastFunction = (toastFn: (message: string) => void) => {
showToast = toastFn;
};
export const setLogoutFunction = (logoutFn: () => Promise<void>) => {
globalLogout = logoutFn;
};
// 创建 axios 实例
const api = axios.create({
baseURL: 'https://testlu.chuangtewl.com/prod-api',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器
api.interceptors.request.use(
async (config) => {
if (__DEV__) {
console.log('[Request]:', config.url, config.data);
}
const token = await auth.getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// 响应拦截器
api.interceptors.response.use(
response => {
if (__DEV__) {
console.log('[Response]:', response.config.url, response.data);
}
const { code, msg, data } = response.data;
if (code === 401) {
auth.removeToken();
globalLogout?.();
showToast?.('登录已过期,请重新登录');
return Promise.reject(response.data);
}
if (code !== 200) {
showToast?.(msg || '服务器错误');
return Promise.reject(response.data);
}
return response.data;
},
error => {
if (__DEV__) {
console.log('[Response Error]:', error.config?.url, error.message);
}
const errorMsg = error.message === 'Network Error'
? '网络连接失败,请检查网络设置'
: (error.response?.data?.msg || '请求失败,请稍后重试');
showToast?.(errorMsg);
return Promise.reject(error);
}
);
// API 方法
export const apiService = {
getPhoneCode: (phone: string, type: string) =>
api.get('/appCaptcha', { params: { phone, type } }),
phoneCodeLogin: (phone: string, phoneCode: string, uuid: string) =>
api.post('/appCodeLogin', { phone, phoneCode, uuid }),
passwordLogin: (username: string, password: string) =>
api.post('/appLogin', { username, password }),
register: (username: string, password: string, code: string, uuid: string) =>
api.post('/register', { username, password, code, uuid }),
resetPassword: (phone: string, newPassword: string, phoneCode: string, uuid: string) =>
api.post('/forgotPassword', { phone, newPassword, phoneCode, uuid }),
getUserInfo: () => api.get('/getInfo'),
getDeviceInfo: (sn: string) =>
api.get('/appVerify/getDeviceBySn', { params: { sn } }),
bindSn: (sn: string) =>
api.post('/appVerify/userBandDevice?sn=' + sn),
getDeviceList: () => api.get('/appVerify/getDeviceListByToken'),
};