猫妈狗爸伴宠师小程序前端代码
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.

80 lines
2.0 KiB

11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
  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. if (getToken()) {
  23. config.header['Authorization'] = 'Bearer ' + getToken()
  24. }
  25. // get请求映射params参数
  26. if (config.params) {
  27. let url = config.url + '?' + tansParams(config.params)
  28. url = url.slice(0, -1)
  29. config.url = url
  30. }
  31. return new Promise((resolve, reject) => {
  32. uni.request({
  33. method: config.method || 'get',
  34. timeout: config.timeout || timeout,
  35. url: config.baseUrl || baseUrl + config.url,
  36. data: config.data,
  37. header: config.header,
  38. dataType: 'json'
  39. }).then(res => {
  40. const code = res.data.code || 200
  41. const msg = errorCode[code] || res.data.msg || errorCode['default']
  42. if (code === 401) {
  43. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  44. if (res.confirm) {
  45. store.dispatch('login').then(res => {
  46. uni.reLaunch({
  47. url: '/pages/index'
  48. })
  49. })
  50. }
  51. })
  52. reject('无效的会话,或者会话已过期,请重新登录。')
  53. } else if (code === 500) {
  54. toast(msg)
  55. reject('500')
  56. } else if (code !== 200) {
  57. toast(msg)
  58. reject(code)
  59. }
  60. resolve(res.data)
  61. })
  62. .catch(error => {
  63. // let {
  64. // message
  65. // } = error
  66. // if (message === 'Network Error') {
  67. // message = '后端接口连接异常'
  68. // } else if (message.includes('timeout')) {
  69. // message = '系统接口请求超时'
  70. // } else if (message.includes('Request failed with status code')) {
  71. // message = '系统接口' + message.substr(message.length - 3) + '异常'
  72. // }
  73. // toast(message)
  74. reject(error)
  75. })
  76. })
  77. }
  78. export default request