猫妈狗爸伴宠师小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.1 KiB

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