request.js 2.6 KB

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