config.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import ENV_CONFIG from '@/.env.js'
  2. import { silentLogin } from './auth'
  3. // api前缀
  4. export const HTTP_URL_DEV_PREFIX = '/api'
  5. export const HTTP_URL_PROD_PREFIX = '/api'
  6. const env = ENV_CONFIG[process.env.ENV_TYPE || 'dev'];
  7. // 基于uview-ui的http配置
  8. export const UVIEWUI_HTTP_CONFIG = {
  9. // 地址
  10. baseUrl: env.apiUrl + env.apiUrlPrefix,
  11. // 请求方式
  12. method: 'post',
  13. // 参数类型
  14. dataType: 'json',
  15. // 是否显示请求中的loading
  16. showLoading: true,
  17. // 请求loading中的文字提示
  18. loadingText: '请求中...',
  19. // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
  20. loadingTime: 800,
  21. // 是否在拦截器中返回服务端的原始数据
  22. originalData: true,
  23. // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
  24. loadingMask: true,
  25. // header:{
  26. // token:uni.getStorageSync('token')
  27. // },
  28. }
  29. // 此处配置请求拦截器
  30. export const httpRequest = (config) => {
  31. const token = uni.getStorageSync('token');
  32. config.header.Authorization = token ? `Bearer ${token}` : ''
  33. return config;
  34. }
  35. // 此处配置响应拦截器
  36. export const httpResponse = (res) => {
  37. return new Promise(function(resolve, reject) {
  38. if (res.statusCode == 200) {
  39. console.log('成功>>>>', res.data);
  40. if (res.data.code !== 200) {
  41. uni.showToast({
  42. icon: 'none',
  43. title: res.data.msg
  44. })
  45. return reject(res.data);
  46. }
  47. if (res.data.code == 401) {
  48. console.log('接口未登录>>>>401');
  49. // 尝试静默登录
  50. silentLogin()
  51. .then((data) => {
  52. // 登录成功,重新发起之前失败的请求
  53. uni.$u.http.request(res.config).then(resolve).catch(reject);
  54. })
  55. .catch(() => {
  56. // 登录失败,跳转首页
  57. uni.switchTab({
  58. url: '/pages/home/index'
  59. });
  60. reject(res.data);
  61. });
  62. return;
  63. }
  64. return resolve(res.data);
  65. }
  66. if (res.statusCode == 401) {
  67. console.log('接口未登录>>>>401',res);
  68. silentLogin()
  69. .then((data) => {
  70. // 登录成功,重新发起之前失败的请求
  71. uni.$u.http.request(res.config).then(resolve).catch(reject);
  72. })
  73. .catch(() => {
  74. // 登录失败,跳转首页
  75. uni.switchTab({
  76. url: '/pages/home/index'
  77. });
  78. reject(res.data);
  79. });
  80. return;
  81. }
  82. if (res.statusCode == 500) {
  83. console.log('服务器异常>>>>500', res.config);
  84. uni.showToast({
  85. title: '服务器异常,请联系客服!',
  86. icon: 'none',
  87. duration: 3000
  88. })
  89. return reject(res.data);
  90. }
  91. return resolve(res.data);
  92. })
  93. }
  94. // http安装方法
  95. export const installHttpConfig = (Vue, vm) => {
  96. Vue.prototype.$u.http.setConfig(UVIEWUI_HTTP_CONFIG);
  97. Vue.prototype.$u.http.interceptor.request = httpRequest
  98. Vue.prototype.$u.http.interceptor.response = httpResponse
  99. }