request.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import {
  2. getToken,
  3. setToken
  4. } from './auth.js'
  5. import {
  6. toast
  7. } from './common.js'
  8. import { login } from '@/api/login.js'
  9. import config from '../config.js'
  10. const BASE_URL = config.service
  11. const request = config => {
  12. config.header = config.header || {}
  13. if (getToken()) {
  14. config.header['Authorization'] = 'Bearer ' + getToken()
  15. reqFunc(config)
  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: { code: loginInfo.code },
  32. }).then((response) => {
  33. if (response.statusCode === 200) {
  34. const { code, data, msg } = response.data
  35. if (data && data.openId) {
  36. setToken(data.token.access_token)
  37. config.header['Authorization'] = 'Bearer ' + getToken()
  38. reqFunc(config)
  39. } else {
  40. uni.showModal({
  41. title: '系统提示',
  42. content: '该微信还未绑定账号,请去绑定',
  43. showCancel: false,
  44. success: function(res) {
  45. if (res.confirm) {
  46. uni.reLaunch({
  47. url: '/pages/login/login'
  48. })
  49. }
  50. }
  51. });
  52. }
  53. } else {
  54. toast('系统未知错误,请反馈给管理员')
  55. }
  56. })
  57. }
  58. })
  59. }
  60. }
  61. const reqFunc = config => {
  62. return new Promise((resolve, reject) => {
  63. uni.request({
  64. header: config.header,
  65. method: config.method.toUpperCase() || 'GET',
  66. dataType: 'json',
  67. timeout: config.timeout || 10000,
  68. url: BASE_URL + config.url,
  69. data: config.data,
  70. }).then((res) => {
  71. if (res.statusCode === 200) {
  72. const { code, msg } = res.data
  73. if (code !== 200) {
  74. toast(msg)
  75. reject(code)
  76. }
  77. resolve(res.data)
  78. } else {
  79. toast('未知错误,请反馈给管理员')
  80. }
  81. }).catch(error => {
  82. let {
  83. message
  84. } = error
  85. if (message === 'Network Error') {
  86. message = '后端接口连接异常'
  87. } else if (message.includes('timeout')) {
  88. message = '系统接口请求超时'
  89. } else if (message.includes('Request failed with status code')) {
  90. message = '系统接口' + message.substr(message.length - 3) + '异常'
  91. }
  92. toast(message)
  93. reject(error)
  94. })
  95. })
  96. }
  97. export default request