Utils

coderljw 2024-10-13 Uni App
  • Uni App
  • Utils
大约 2 分钟

# 1. Fly 请求封装

import storage from './storage'
import qs from 'qs'
import { baseUrl } from '@/config'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const loginPath = 'subPages/login/index'

// 浏览器和React Native
// const Fly = require('flyio/dist/npm/fly')
// 微信小程序
const Fly = require('flyio/dist/npm/wx')
const fly = new Fly()

//设置超时
fly.config.timeout = 30000
//设置请求基地址
fly.config.baseURL = baseUrl

const showToast = title =>
  uni.showToast({
    title,
    icon: 'none',
    position: 'bottom',
  })

const codeMessage = {
  400: '请求错误',
  401: '请重新登录',
  403: '拒绝访问',
  404: '请求地址错误',
  500: '服务器错误',
  502: '网关错误',
  503: '服务不可用',
  504: '网关超时',
}

const layout = () => {
  storage.remove(ACCESS_TOKEN)
  setTimeout(() => {
    const pathname = getCurrentPages().slice(-1)[0].route
    if (pathname !== loginPath) {
      uni.reLaunch({ url: loginPath })
    }
  }, 1500)
  uni.hideToast()
  showToast(codeMessage[401])
}

// 异常拦截器
const errorHandler = error => {
  uni.hideLoading()
  uni.stopPullDownRefresh()
  if (error.response) {
    const status = error.response.status
    if (status === 401) layout()
    else {
      codeMessage[status] && showToast(codeMessage[status])
    }
  }

  return Promise.reject(error)
}

// 请求拦截器
fly.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  if (token) config.headers['Authorization'] = token

  // 处理GET请求时参数携带数组情况
  if (config.method === 'get') {
    config.paramsSerializer = params =>
      qs.stringify(params, { arrayFormat: 'repeat' })
  }

  return config
}, errorHandler)

// 响应拦截器
fly.interceptors.response.use(({ data }) => {
  uni.hideLoading()
  uni.stopPullDownRefresh()
  const map = {
    401: () => {
      layout()
      return Promise.reject(data)
    },
    200: () => data,
    default: () => {
      message.error(data?.errorMsg || '请求错误')
      return Promise.reject(data)
    },
  }

  return map[data.code]?.() || map.default()
}, errorHandler)

export default fly
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

# 2. storage 封装

  • 新增有效期设置。
class Storage {
  set(key, val, exp) {
    try {
      uni.setStorageSync(key, { val, exp, time: Date.now() })
    } catch (e) {
      console.log(e)
    }
  }
  get(key) {
    try {
      const data = uni.getStorageSync(key)
      if (!data) return null
      if (Date.now() - data.time > data.exp) {
        this.remove(key)
        return null
      }
      return data.val
    } catch (e) {
      console.log(e)
    }
  }
  getInfo() {
    try {
      return uni.getStorageInfoSync()
    } catch (e) {
      console.log(e)
    }
  }
  has(key) {
    try {
      return !!this.get(key)
    } catch (e) {
      console.log(e)
    }
  }
  remove(key) {
    try {
      uni.removeStorageSync(key)
    } catch (e) {
      console.log(e)
    }
  }
  clear() {
    try {
      uni.clearStorageSync()
    } catch (e) {
      console.log(e)
    }
  }
}

export default new Storage()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

# 3. helper

  • main.js

    import helper from './utils/helper'
    Vue.use(helper)
    
    1
    2
  • helper.js

    const helper = {
      $log: console.log,
      $mainColor: '#00D1FF',
      $bgColor: '#121522',
      $errorColor: '#E05164',
      $back: uni.navigateBack,
      $toFixed: (val, exp) => {
        return [void 0, NaN].includes(val)
          ? (0).toFixed(exp)
          : (Math.round(val * Math.pow(10, exp)) / Math.pow(10, exp)).toFixed(exp)
      },
    }
    
    export default {
      install(Vue) {
        Object.entries(helper).forEach(
          ([key, value]) => (Vue.prototype[key] = value)
        )
      },
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

注意

小程序 Vue 原型中定义的属性,在 template 中不可用。

以父之名
周杰伦.mp3