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.1 KiB

  1. import { useUserStore } from "../stores/modules/userInfo";
  2. const baseURL = "https://hwjb.homilychart.com/testApi"
  3. const httpInterceptor = {
  4. // 拦截前触发
  5. invoke(options) {
  6. // 1.非http
  7. if (!options.url.startsWith('http')) {
  8. options.url = baseURL + options.url
  9. }
  10. // 2.请求超时,默认60s
  11. options.timeout = 60000
  12. console.log(options)
  13. //3 添加小程序端请求头
  14. options.header = {
  15. ...options.header,
  16. 'source-client': 'miniapp'
  17. }
  18. //4 添加token
  19. const memberStore = useUserStore()
  20. const token = memberStore.userInfo?.token
  21. if (token) {
  22. options.header.Authorization = token
  23. }
  24. return options
  25. }
  26. }
  27. // 添加拦截器
  28. uni.addInterceptor('request', httpInterceptor)
  29. uni.addInterceptor('uploadFile', httpInterceptor)
  30. // 添加请求函数
  31. export const http = (options) => {
  32. return new Promise((resolve, reject) => {
  33. uni.request({
  34. ...options,
  35. // 1.请求成功
  36. success: (result) => {
  37. if (result.statusCode >= 200 && result.statusCode < 300) {
  38. resolve(result.data)
  39. } else if (result.statusCode === 401) {
  40. // 清除登录信息
  41. const memberStore = useUserStore()
  42. memberStore.clearUserInfo()
  43. // 提示用户重新登录
  44. uni.navigateTo({
  45. url: '/pages/login/login'
  46. })
  47. reject(result)
  48. } else {
  49. uni.showToast({
  50. title: (result.data).msg || '请求失败',
  51. icon: 'none'
  52. })
  53. reject(result)
  54. }
  55. },
  56. // 2.请求失败
  57. fail: (err) => {
  58. reject(err)
  59. uni.showToast({
  60. title: '网络错误',
  61. icon: 'none'
  62. })
  63. }
  64. })
  65. })
  66. }