request.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { getToken, setToken } from './auth.js'
  2. import { toast } from './common.js'
  3. import config from '../config.js'
  4. const BASE_URL = config.service
  5. const request = config => {
  6. config.header = config.header || {}
  7. let isRequest = false
  8. if (getToken()) {
  9. config.header['Authorization'] = 'Bearer ' + getToken()
  10. isRequest = true
  11. } else {
  12. uni.login({ // 获取用户登录凭证换取openid
  13. provider: 'weixin',
  14. success: (loginInfo) => {
  15. login({ code: loginInfo.code }).then((response) => {
  16. if (response.statusCode === 200) {
  17. const { code, data, msg } = response.data
  18. if (data && data.openId) {
  19. setToken(data.token.access_token)
  20. uni.setStorageSync('userInfo', data.sysUser)
  21. config.header['Authorization'] = 'Bearer ' + getToken()
  22. isRequest = true
  23. } else {
  24. uni.showModal({
  25. title: '系统提示',
  26. content: '该微信还未绑定账号,请去绑定',
  27. showCancel: false,
  28. success: function(res) {
  29. if (res.confirm) {
  30. uni.reLaunch({
  31. url: '/pages/login/login'
  32. })
  33. }
  34. }
  35. });
  36. }
  37. } else {
  38. toast('系统未知错误,请反馈给管理员')
  39. }
  40. })
  41. }
  42. })
  43. }
  44. if (isRequest) {
  45. return new Promise((resolve, reject) => {
  46. uni.request({
  47. header: config.header,
  48. method: config.method.toUpperCase() || 'GET',
  49. dataType: 'json',
  50. timeout: config.timeout || 10000,
  51. url: BASE_URL + config.url,
  52. data: config.data,
  53. }).then((res) => {
  54. // console.log("请求返回:", res)
  55. if (res.statusCode === 200) {
  56. const { code, msg } = res.data
  57. if (code === 401) {
  58. uni.showModal({
  59. title: '系统提示',
  60. content: '登录状态已过期,请重新登录',
  61. showCancel: false,
  62. success: function(res) {
  63. if (res.confirm) {
  64. uni.reLaunch({
  65. url: '/pages/login/login'
  66. })
  67. }
  68. }
  69. });
  70. } else if (code !== 200) {
  71. toast(msg)
  72. reject(code)
  73. }
  74. resolve(res.data)
  75. } else {
  76. toast('未知错误,请反馈给管理员')
  77. }
  78. }).catch(error => {
  79. console.log("error", error)
  80. let {
  81. message
  82. } = error
  83. if (message === 'Network Error') {
  84. message = '后端接口连接异常'
  85. } else if (message.includes('timeout')) {
  86. message = '系统接口请求超时'
  87. } else if (message.includes('Request failed with status code')) {
  88. message = '系统接口' + message.substr(message.length - 3) + '异常'
  89. }
  90. toast(message)
  91. reject(error)
  92. })
  93. })
  94. }
  95. }
  96. export default request