request.ts 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // utils/request.ts
  2. import { useUserStore } from '../store/user'
  3. // const baseURL = 'http://localhost:8888/api'; // 本地开发
  4. // const baseURL = 'http://8.130.28.19:8060/api'; // 测试环境
  5. const baseURL = 'https://eai-wx.seec.seecoder.cn/api';// 正式环境
  6. // 不需要认证的接口路径列表
  7. const noAuthUrls = [
  8. '/login', // 登录接口
  9. '/sms-code' // 发送验证码接口
  10. // ... 其他不需要认证的接口,如注册、找回密码等
  11. ];
  12. export const request = <T = any>(options: {
  13. url: string; // 这里的 url 是相对路径,例如 '/sms-code'
  14. method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  15. data?: any;
  16. header?: Record<string, string>;
  17. params?: Record<string, string | number>;
  18. // 【新增】一个选项,可以显式覆盖是否需要认证,用于特殊情况
  19. requireAuth?: boolean;
  20. }): Promise<T> => {
  21. const userStore = useUserStore();
  22. let requestUrl = baseURL + options.url;
  23. if (options.params) {
  24. const queryString = Object.keys(options.params)
  25. .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(options.params![key])}`)
  26. .join('&');
  27. requestUrl += `?${queryString}`;
  28. }
  29. // 【核心修改】判断当前请求是否需要认证
  30. const token = userStore.token;
  31. // 默认需要认证,除非url在noAuthUrls中,或者options.requireAuth明确为false
  32. let shouldAttachAuthHeader = true;
  33. if (options.requireAuth === false || noAuthUrls.includes(options.url)) {
  34. shouldAttachAuthHeader = false;
  35. }
  36. // 如果明确要求认证,但没有token,则保持应该附带,但header会是空字符串
  37. if (options.requireAuth === true) {
  38. shouldAttachAuthHeader = true;
  39. }
  40. return new Promise((resolve, reject) => {
  41. uni.request({
  42. url: requestUrl,
  43. method: options.method || 'GET',
  44. data: options.data || {},
  45. header: {
  46. 'Content-Type': 'application/json',
  47. // 【核心修改】根据 shouldAttachAuthHeader 判断是否添加 Authorization 头
  48. ...(shouldAttachAuthHeader && token ? { 'Authorization': ` ${token}` } : {}),
  49. // ...(shouldAttachAuthHeader && token ? { 'Authorization': `Bearer ${token}` } : {}),
  50. ...options.header // 允许外部传入覆盖或添加其他header
  51. },
  52. success: (res: UniApp.RequestSuccessCallbackResult) => {
  53. const responseData = res.data; // responseData 没有类型定义
  54. if (responseData.code === 200) {
  55. resolve(responseData.data);
  56. } else {
  57. uni.showToast({
  58. title: responseData.message || '操作失败',
  59. icon: 'none'
  60. });
  61. reject(responseData);
  62. }
  63. },
  64. fail: (err: UniApp.RequestFailCallbackResult) => {
  65. uni.showToast({
  66. title: '网络错误,请稍后重试',
  67. icon: 'none'
  68. });
  69. reject(err);
  70. }
  71. });
  72. });
  73. };