request.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. setToken(data.token.access_token)
  43. config.header['Authorization'] = 'Bearer ' + getToken()
  44. isRequest = true
  45. } else {
  46. uni.showModal({
  47. title: '系统提示',
  48. content: '该微信还未绑定账号,请去绑定',
  49. showCancel: false,
  50. success: function(res) {
  51. if (res.confirm) {
  52. uni.reLaunch({
  53. url: '/pages/login/login'
  54. })
  55. }
  56. }
  57. });
  58. }
  59. } else {
  60. toast('系统未知错误,请反馈给管理员')
  61. }
  62. })
  63. }
  64. })
  65. }
  66. if (isRequest) {
  67. console.log("请求", config)
  68. return new Promise((resolve, reject) => {
  69. uni.request({
  70. header: config.header,
  71. method: config.method.toUpperCase() || 'GET',
  72. dataType: 'json',
  73. timeout: config.timeout || 10000,
  74. url: BASE_URL + config.url,
  75. data: config.data,
  76. }).then((res) => {
  77. console.log("请求返回:", res)
  78. if (res.statusCode === 200) {
  79. const {
  80. code,
  81. msg
  82. } = res.data
  83. if (code !== 200) {
  84. toast(msg)
  85. reject(code)
  86. }
  87. resolve(res.data)
  88. } else {
  89. toast('未知错误,请反馈给管理员')
  90. }
  91. }).catch(error => {
  92. console.log("error", error)
  93. let {
  94. message
  95. } = error
  96. if (message === 'Network Error') {
  97. message = '后端接口连接异常'
  98. } else if (message.includes('timeout')) {
  99. message = '系统接口请求超时'
  100. } else if (message.includes('Request failed with status code')) {
  101. message = '系统接口' + message.substr(message.length - 3) + '异常'
  102. }
  103. toast(message)
  104. reject(error)
  105. })
  106. })
  107. }
  108. }
  109. export default request