request.js 2.2 KB

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