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

69 lines
2.5 KiB

  1. import {store} from '@/store'
  2. import {getToken} from '@/utils/auth'
  3. import errorCode from '@/utils/errorCode'
  4. import {showConfirm, tansParams, toast} from '@/utils/common'
  5. import {currentUrl} from '@/utils/getUrl'
  6. let timeout = 10000
  7. const baseUrl = currentUrl
  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. return new Promise((resolve, reject) => {
  22. uni.request({
  23. method: config.method || 'get',
  24. timeout: config.timeout || timeout,
  25. url: config.baseUrl || baseUrl + config.url,
  26. data: config.data,
  27. header: config.header,
  28. dataType: 'json'
  29. }).then(res => {
  30. console.log(res);
  31. const code = res.data.code || 200
  32. console.log(code);
  33. const msg = errorCode[code] || res.data.msg || errorCode['default']
  34. if (code === 401) {
  35. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  36. if (res.confirm) {
  37. store.dispatch('LogOut').then(res => {
  38. uni.reLaunch({url: '/pages/index'})
  39. })
  40. }
  41. })
  42. reject('无效的会话,或者会话已过期,请重新登录。')
  43. } else if (code === 500) {
  44. toast(msg)
  45. reject('500')
  46. } else if (code !== 200) {
  47. toast(msg)
  48. reject(code)
  49. }
  50. resolve(res.data)
  51. })
  52. .catch(error => {
  53. let {message} = error
  54. if (message === 'Network Error') {
  55. message = '后端接口连接异常'
  56. } else if (message.includes('timeout')) {
  57. message = '系统接口请求超时'
  58. } else if (message.includes('Request failed with status code')) {
  59. message = '系统接口' + message.substr(message.length - 3) + '异常'
  60. }
  61. toast(message)
  62. reject(error)
  63. })
  64. })
  65. }
  66. export default request