You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.9 KiB

7 months ago
7 months ago
  1. import { H5_API, WX_API,httpPrefix } from './site.config.js'
  2. const ContentType = ['application/json;charset=utf-8', 'application/x-www-form-urlencoded','multipart/form-data', 'application/x-www-form-urlencoded; charset=UTF-8'];
  3. // 此vm参数为页面的实例,可以通过它引用vuex中的变量
  4. module.exports = (vm) => {
  5. // 初始化请求配置
  6. uni.$u.http.setConfig((config) => {
  7. let prefix = config.custom.prefix?config.custom.prefix: httpPrefix
  8. /* config 为默认全局配置*/
  9. config.baseURL = H5_API+ WX_API + prefix; /* 根域名 */
  10. // console.log(config)
  11. config.header['tenant-id'] = vm.$store.state.user.vuex_TenantId
  12. // config.dataType= 'xml'
  13. return config
  14. })
  15. // 请求拦截
  16. uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  17. let contentTypeIndex = config.header.contentType
  18. if(contentTypeIndex) {
  19. // alert(contentTypeIndex)
  20. config.header['content-type'] = ContentType[contentTypeIndex]
  21. }else {
  22. config.header['content-type'] = 'application/json;charset=utf-8'
  23. }
  24. // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
  25. config.data = config.data || {}
  26. // 根据custom参数中配置的是否需要token,添加对应的请求头
  27. let token = vm.$store.state.user.vuex_loginInfo.accessToken
  28. if(token) {
  29. config.header.Authorization = 'Bearer ' + token
  30. }
  31. let noToken = config.custom?.noToken
  32. if(noToken&&config.header.Authorization) {
  33. delete config.header.Authorization
  34. }
  35. return config
  36. }, config => { // 可使用async await 做异步操作
  37. return Promise.reject(config)
  38. })
  39. // 响应拦截
  40. uni.$u.http.interceptors.response.use(async (response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
  41. const data = response.data
  42. if(data.code==406&&response.config.url!='system/auth/refresh-token') {
  43. await vm.$store.dispatch('refreshToken')
  44. let obj = response.config
  45. let method = obj.method.toLowerCase()
  46. if(method=='get') {
  47. return uni.$u.http[method](obj.url, {params: obj.params})
  48. }else{
  49. return uni.$u.http[method](obj.url, obj.data )
  50. }
  51. }
  52. if(data.code==401) {
  53. vm.$store.commit('goLogin')
  54. }
  55. // 自定义参数
  56. const custom = response.config?.custom
  57. if (data.code !== 0) {
  58. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  59. if (custom.toast !== false) {
  60. uni.$u.toast(data.msg)
  61. }
  62. // 如果需要catch返回,则进行reject
  63. if (custom?.catch) {
  64. return Promise.reject(data)
  65. } else {
  66. // 否则返回一个pending中的promise,请求不会进入catch中
  67. return new Promise(() => { })
  68. }
  69. }
  70. return data === undefined ? {} : data
  71. }, (response) => {
  72. // 对响应错误做点什么 (statusCode !== 200)
  73. return Promise.reject(response)
  74. })
  75. }