request.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. }
  14. // else {
  15. // config.header['Authorization'] = 'Bearer ' +
  16. // 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjo3MDA0NDMsInVzZXJfa2V5IjoiNjFlMDVkMWItODY1Zi00MGIwLThiOWItM2VjY2I0ZGEzYjAwIiwidXNlcm5hbWUiOiJ5bGpnMjIwMjgyMDAzMiJ9.K16sZmP0X54BsIt5dpPBm5Jw8VLoQR3Vt1VJ8IpdRNChDwZNthxfCBAKPkUAilFtb5NuBIppH54dktTPSV5mNA'
  17. // }
  18. uni.showLoading({
  19. title: '请求中...'
  20. })
  21. console.log("请求:", config)
  22. return new Promise((resolve, reject) => {
  23. uni.request({
  24. header: config.header,
  25. method: config.method.toUpperCase() || 'GET',
  26. dataType: 'json',
  27. timeout: config.timeout || 10000,
  28. url: BASE_URL + config.url,
  29. data: config.data,
  30. }).then((res) => {
  31. console.log("请求成功:", res)
  32. const code = res.statusCode || 200
  33. const msg = res.data.msg || '未知错误,请反馈给管理员'
  34. // if (res.data.code === 500) {
  35. // uni.showToast({
  36. // icon: 'error',
  37. // title: '接口未知异常',
  38. // })
  39. // reject(msg)
  40. // }
  41. if (code === 401) {
  42. uni.showModal({
  43. title: '错误提示',
  44. content: msg,
  45. showCancel: false,
  46. success: function(res) {
  47. if (res.confirm) {
  48. uni.reLaunch({
  49. url: '/pages/login/login'
  50. })
  51. }
  52. }
  53. });
  54. reject(msg)
  55. } else if (code !== 200) {
  56. toast(msg)
  57. reject(code)
  58. }
  59. uni.hideLoading()
  60. resolve(res.data)
  61. }).catch(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