request.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. return new Promise((resolve, reject) => {
  19. uni.request({
  20. header: config.header,
  21. method: config.method.toUpperCase() || 'GET',
  22. dataType: 'json',
  23. timeout: config.timeout || 10000,
  24. url: BASE_URL + config.url,
  25. data: config.data,
  26. }).then((res) => {
  27. console.log("请求成功:", res)
  28. const code = res.statusCode || 200
  29. const msg = res.data.msg || '未知错误,请反馈给管理员'
  30. if (res.data.code == 500) {
  31. uni.showToast({
  32. icon:'error',
  33. title: '接口未知异常',
  34. })
  35. reject(msg)
  36. }
  37. if (code === 401) {
  38. uni.showModal({
  39. title: '错误提示',
  40. content: msg,
  41. showCancel: false,
  42. success: function(res) {
  43. if (res.confirm) {
  44. uni.reLaunch({
  45. url: '/pages/login/login'
  46. })
  47. }
  48. }
  49. });
  50. reject(msg)
  51. } else if (code !== 200) {
  52. toast(msg)
  53. reject(code)
  54. }
  55. resolve(res.data.data)
  56. }).catch(error => {
  57. console.log("请求失败:", error)
  58. let {
  59. message
  60. } = error
  61. if (message === 'Network Error') {
  62. message = '后端接口连接异常'
  63. } else if (message.includes('timeout')) {
  64. message = '系统接口请求超时'
  65. } else if (message.includes('Request failed with status code')) {
  66. message = '系统接口' + message.substr(message.length - 3) + '异常'
  67. }
  68. toast(message)
  69. reject(error)
  70. })
  71. })
  72. }
  73. export default request