Blame view

common/utils/request.js 2.37 KB
c293da23   刘淇   新园林init
1
2
3
4
5
6
7
8
9
  import globalConfig from '@/common/config/global';
  import cache from '@/common/utils/cache';
  import { useUserStore } from '@/pinia/user';
  
  const request = (options) => {
    const defaultOptions = {
      url: '',
      method: 'GET',
      data: {},
ee792d52   刘淇   动态表单
10
11
12
13
      header: { 
        'Content-Type': 'application/json',
        'tenant-id':'1'
       },
c293da23   刘淇   新园林init
14
15
16
17
18
19
20
21
22
23
24
25
26
27
      timeout: globalConfig.api.timeout
    };
  
    const opts = { ...defaultOptions, ...options };
    let token = '';
    try {
      const userStore = useUserStore();
      token = userStore.token || cache.get(globalConfig.cache.tokenKey);
    } catch (err) {
      token = cache.get(globalConfig.cache.tokenKey);
    }
  
    if (token) {
      opts.header['Authorization'] = `Bearer ${token}`;
50ad810a   王彪总   业务线 小程序不用写死,从后端接口获取
28
29
30
31
    } else if (globalConfig.tenantId) {
      // 多租户:未登录时后端无法从 token 推导租户,必须显式携带 tenant-id(登录、刷新令牌等接口)
      // 已登录请求由后端按 token 取租户,故不硬编码此头,避免将来多租户下跨租户 403
      opts.header['tenant-id'] = String(globalConfig.tenantId);
c293da23   刘淇   新园林init
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    }
  
    opts.url = globalConfig.api.baseUrl + opts.url;
  
    return new Promise((resolve, reject) => {
      uni.request({
        ...opts,
        success: (res) => {
          if (res.statusCode === 200) {
            const { code, data, msg } = res.data;
            if (code === 0) {
              resolve(data);
            } else if (code === 401) {
              const userStore = useUserStore();
              userStore.logout();
              uni.showToast({ title: msg || '登录过期', icon: 'none' });
              reject(res.data);
            } else {
              uni.showToast({ title: msg || '请求失败', icon: 'none' });
              reject(res.data);
            }
          } else {
            uni.showToast({ title: `错误:${res.statusCode}`, icon: 'none' });
            reject(res);
          }
        },
        fail: (err) => {
          uni.showToast({ title: '网络失败', icon: 'none' });
          reject(err);
        }
      });
    });
  };
  
  export const get = (url, data = {}, options = {}) => request({ url, method: 'GET', data, ...options });
  export const post = (url, data = {}, options = {}) => request({ url, method: 'POST', data, ...options });
  export const put = (url, data = {}, options = {}) => request({ url, method: 'PUT', data, ...options });
  export const del = (url, data = {}, options = {}) => request({ url, method: 'DELETE', data, ...options });
  
  export default request;