http.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { useUserStore } from '@/stores/user'
  2. import config from './config'
  3. import utils from './utils'
  4. import { convertUrlParams } from '@/utils/share'
  5. const request = (method, url, data, opt) => {
  6. const userStore = useUserStore()
  7. opt.showLoading && uni.showLoading({
  8. title: opt.loadingTitle,
  9. mask: method === 'POST' ? true : false
  10. })
  11. return uni.request({
  12. method,
  13. url: utils.isHttp(url) ? url : config.apiBaseUrl + url,
  14. header: {
  15. Authorization: userStore.token || '',
  16. ...opt.header
  17. },
  18. data
  19. }).then(res => {
  20. const { statusCode, data } = res
  21. const { code, errCode, msg, success } = data || {}
  22. if (statusCode === 401 && [100002, 100003].includes(code)) {
  23. uni.showToast({
  24. title: '登录已过期,即将重新登录...',
  25. icon: 'none'
  26. })
  27. const pages = getCurrentPages();
  28. const currentPage = pages[pages.length - 1]
  29. const route = ('/' + currentPage.route) || '/pages/index/index'
  30. const options = Object.keys(currentPage.options).length ? currentPage.options : {}
  31. const params = convertUrlParams({ ...options, sharePath: route })
  32. setTimeout(() => {
  33. uni.redirectTo({
  34. url: `/pages/index/welcome${params}`
  35. })
  36. }, 1500);
  37. return data
  38. } else {
  39. if (!success) {
  40. uni.showToast({
  41. title: msg || '请求失败',
  42. icon: 'none'
  43. })
  44. }
  45. return data
  46. }
  47. }).catch(err => {
  48. uni.showToast({
  49. title: err.msg || '请求失败',
  50. icon: 'none'
  51. })
  52. }).finally(() => {
  53. opt.showLoading && uni.hideLoading({ noConflict: true })
  54. })
  55. }
  56. const http = {}
  57. const methods = ['GET', 'POST', 'PUT', 'DELETE']
  58. methods.forEach(method => {
  59. http[method.toLowerCase()] = (url, data, options) => {
  60. const loadingTitle = method === 'GET' ? '加载中...' : '提交中...'
  61. const opt = Object.assign({
  62. loadingTitle
  63. },
  64. config.httpDefaultOption,
  65. options
  66. )
  67. if (opt.isAuth) {
  68. const userStore = useUserStore()
  69. if (!userStore.token) {
  70. // uni.navigateTo({
  71. // url: '/pages/login/login'
  72. // })
  73. // return Promise.reject({
  74. // msg: '无token'
  75. // })
  76. }
  77. }
  78. // 提交数据中值为undefined的改成空字符串
  79. if (typeof data === 'object') {
  80. for (let key in data) {
  81. if (data[key] === 'undefined') {
  82. data[key] = ''
  83. }
  84. }
  85. }
  86. return request(method, url, data, opt)
  87. }
  88. })
  89. export default http