request.js 2.5 KB

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