request.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // import store from '@/store'
  2. import config from '@/config'
  3. import { getToken } from '@/utils/auth'
  4. import errorCode from '@/utils/errorCode'
  5. import { toast, showConfirm, tansParams } from '@/utils/common'
  6. let timeout = 10000
  7. const baseUrl = config.baseUrl
  8. const request = config => {
  9. // 是否需要设置 token
  10. // const isToken = (config.headers || {}).isToken === false
  11. config.header = config.header || {}
  12. // if (getToken() && !isToken) {
  13. // config.header['Authorization'] = 'Bearer ' + getToken()
  14. // }
  15. // get请求映射params参数
  16. if (config.params) {
  17. let url = config.url + '?' + tansParams(config.params)
  18. url = url.slice(0, -1)
  19. config.url = url
  20. }
  21. console.log('request.data', config.data);
  22. return new Promise((resolve, reject) => {
  23. uni.request({
  24. method: config.method || 'get',
  25. timeout: config.timeout || timeout,
  26. url: config.baseUrl || baseUrl + config.url,
  27. data: config.data,
  28. header: config.header,
  29. dataType: 'json'
  30. }).then(response => {
  31. // let [error, res] = response
  32. const { statusCode, data } = response
  33. const returnCode = data.returnCode
  34. const code = statusCode || 200
  35. const msg = errorCode[code] || data.returnMsg || errorCode['default']
  36. console.log('response', response);
  37. if (returnCode == -201) {
  38. toast(msg)
  39. reject(returnCode)
  40. return
  41. }
  42. if (code === 401) {
  43. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  44. // if (res.confirm) {
  45. // store.dispatch('LogOut').then(res => {
  46. // uni.reLaunch({ url: '/pages/login' })
  47. // })
  48. // }
  49. })
  50. reject('无效的会话,或者会话已过期,请重新登录。')
  51. } else if (code === 500) {
  52. toast(msg)
  53. reject('500')
  54. } else if (code !== 200) {
  55. toast(msg)
  56. reject(code)
  57. }
  58. resolve(data)
  59. })
  60. .catch(error => {
  61. let { message } = error
  62. if (message === 'Network Error') {
  63. message = '后端接口连接异常'
  64. } else if (message.includes('timeout')) {
  65. message = '系统接口请求超时'
  66. } else if (message.includes('Request failed with status code')) {
  67. message = '系统接口' + message.substr(message.length - 3) + '异常'
  68. }
  69. toast(message)
  70. reject(error)
  71. })
  72. })
  73. }
  74. export default request