request.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. //import store from '@/store'
  2. import config from '../config.js'
  3. import {
  4. getAuth
  5. } from '@/utils/auth'
  6. import {
  7. Md5
  8. } from 'ts-md5/dist/md5';
  9. import errorCode from '@/utils/errorCode'
  10. import {
  11. toast,
  12. showConfirm,
  13. tansParams
  14. } from '@/utils/common'
  15. let timeout = 10000
  16. const baseUrl = config.baseUrl
  17. const request = config => {
  18. // 是否需要设置 token
  19. // const isToken = (config.headers || {}).isToken === false
  20. config.header = config.header || {}
  21. // if (getToken() && !isToken) {
  22. // config.headers['X-AUTH-SIGN'] = Md5.hashStr(JSON.stringify(config.data) +auth.secret);
  23. // config.headers['X-AUTH-TOKEN'] = auth.token;
  24. // }
  25. if (getAuth()) {
  26. config.headers['X-AUTH-SIGN'] = Md5.hashStr(JSON.stringify(config.data) + JSON.parse(getAuth()).secret);
  27. config.headers['X-AUTH-TOKEN'] = JSON.parse(getAuth()).token;
  28. }
  29. return new Promise((resolve, reject) => {
  30. // debugger
  31. uni.request({
  32. method: config.method || 'get',
  33. timeout: config.timeout || timeout,
  34. url: config.baseUrl || baseUrl + config.url,
  35. data: config.data,
  36. header: config.headers,
  37. dataType: 'json'
  38. }).then(response => {
  39. const res = response.data;
  40. // if (error) {
  41. // toast('后端接口连接异常')
  42. // reject('后端接口连接异常')
  43. // return
  44. // }
  45. const code = res.code
  46. // const msg = errorCode[code] || res.data.msg || errorCode['default']
  47. if (code === 401) {
  48. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  49. if (res.confirm) {
  50. uni.reLaunch({
  51. url: '/pages/login/index'
  52. })
  53. }
  54. })
  55. reject('无效的会话,或者会话已过期,请重新登录。')
  56. } else if (code === 405) {
  57. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  58. if (res.confirm) {
  59. uni.reLaunch({
  60. url: '/pages/login/index'
  61. })
  62. }
  63. })
  64. reject('无效的会话,或者会话已过期,请重新登录。')
  65. } else if (code === 500) {
  66. reject('500')
  67. } else if (code !== 0) {
  68. // toast(msg)
  69. reject(code)
  70. }
  71. resolve(res)
  72. })
  73. .catch(error => {
  74. let {
  75. message
  76. } = error
  77. if (message === 'Network Error') {
  78. message = '后端接口连接异常'
  79. } else if (message.includes('timeout')) {
  80. message = '系统接口请求超时'
  81. } else if (message.includes('Request failed with status code')) {
  82. message = '系统接口' + message.substr(message.length - 3) + '异常'
  83. }
  84. toast(message)
  85. reject(error)
  86. })
  87. })
  88. }
  89. export default request