request.js 2.7 KB

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