request.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import {
  2. getToken
  3. } from './auth.js'
  4. import {
  5. toast
  6. } from './common.js'
  7. import config from '../config.js'
  8. const BASE_URL = config.service
  9. const request = config => {
  10. config.header = config.header || {}
  11. if (getToken()) {
  12. config.header['Authorization'] = 'Bearer ' + getToken()
  13. } else {
  14. config.header['Authorization'] = 'Bearer ' +
  15. 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjo3MDA0NDMsInVzZXJfa2V5IjoiNjFlMDVkMWItODY1Zi00MGIwLThiOWItM2VjY2I0ZGEzYjAwIiwidXNlcm5hbWUiOiJ5bGpnMjIwMjgyMDAzMiJ9.K16sZmP0X54BsIt5dpPBm5Jw8VLoQR3Vt1VJ8IpdRNChDwZNthxfCBAKPkUAilFtb5NuBIppH54dktTPSV5mNA'
  16. }
  17. console.log("请求:", config, BASE_URL + config.url)
  18. uni.showLoading({
  19. title: '请求中...'
  20. })
  21. return new Promise((resolve, reject) => {
  22. uni.request({
  23. header: config.header,
  24. method: config.method.toUpperCase() || 'GET',
  25. dataType: 'json',
  26. timeout: config.timeout || 10000,
  27. url: BASE_URL + config.url,
  28. data: config.data,
  29. }).then((res) => {
  30. console.log("请求成功:", res)
  31. const code = res.statusCode || 200
  32. const msg = res.data.msg || '未知错误,请反馈给管理员'
  33. if (res.data.code == 500) {
  34. uni.showToast({
  35. icon: 'error',
  36. title: '接口未知异常',
  37. })
  38. reject(msg)
  39. }
  40. if (code === 401) {
  41. uni.showModal({
  42. title: '错误提示',
  43. content: msg,
  44. showCancel: false,
  45. success: function(res) {
  46. if (res.confirm) {
  47. uni.reLaunch({
  48. url: '/pages/login/login'
  49. })
  50. }
  51. }
  52. });
  53. reject(msg)
  54. } else if (code !== 200) {
  55. toast(msg)
  56. reject(code)
  57. }
  58. resolve(res.data.data)
  59. uni.hideLoading()
  60. }).catch(error => {
  61. console.log("请求失败:", error)
  62. let {
  63. message
  64. } = error
  65. if (message === 'Network Error') {
  66. message = '后端接口连接异常'
  67. } else if (message.includes('timeout')) {
  68. message = '系统接口请求超时'
  69. } else if (message.includes('Request failed with status code')) {
  70. message = '系统接口' + message.substr(message.length - 3) + '异常'
  71. }
  72. uni.hideLoading()
  73. toast(message)
  74. reject(error)
  75. })
  76. })
  77. }
  78. export default request