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.

88 lines
3.3 KiB

  1. import { useUserStore } from "../stores/modules/userInfo/"
  2. const baseURL = "https://hwjb.homilychart.com/testApi"
  3. const httpInterceptor = {
  4. // 拦截前触发
  5. invoke(options) {
  6. // 打印当前 baseURL 便于定位来源
  7. console.log('HTTP(baseURL)=', baseURL)
  8. // 若出现旧代码将 url 设为 http://localhost:8888,强制改为真实域名
  9. if (options.url.startsWith('http://localhost:8888')) {
  10. options.url = baseURL.replace(/\/$/, '') + options.url.replace('http://localhost:8888', '')
  11. } else if (options.url.startsWith('https://localhost:8888')) {
  12. options.url = baseURL.replace(/\/$/, '') + options.url.replace('https://localhost:8888', '')
  13. }
  14. // 仅当明确配置了 baseURL 时才拼接前缀(去掉 baseURL 尾部的斜杠,避免双斜杠)
  15. if (baseURL && !options.url.startsWith('http')) {
  16. options.url = baseURL.replace(/\/$/, '') + options.url
  17. }
  18. // 打印最终请求地址
  19. console.log('HTTP(finalUrl)=', options.url)
  20. // 2.请求超时,默认60s
  21. options.timeout = 60000
  22. console.log(options)
  23. //3 添加小程序端请求头
  24. const sys = uni.getSystemInfoSync();
  25. // 为对齐后端文档示例,client 固定为 ios(如需按平台设置再改回)
  26. const client = 'ios';
  27. options.header = {
  28. ...options.header,
  29. 'source-client': 'miniapp',
  30. // 标准头与文档头同时设置,确保兼容
  31. 'content-type': 'application/json',
  32. 'version': '1',
  33. 'client': client,
  34. 'token': '790750702588f1ea79f24dc56ccd5d8a'
  35. }
  36. //4 添加token
  37. const memberStore = useUserStore()
  38. // const token = memberStore.userInfo?.token
  39. const token = '790750702588f1ea79f24dc56ccd5d8a'
  40. if (token) {
  41. options.header.Authorization = token
  42. }
  43. return options
  44. }
  45. }
  46. // 添加拦截器
  47. uni.addInterceptor('request', httpInterceptor)
  48. uni.addInterceptor('uploadFile', httpInterceptor)
  49. // 添加请求函数
  50. export const http = (options) => {
  51. return new Promise((resolve, reject) => {
  52. uni.request({
  53. ...options,
  54. // 1.请求成功
  55. success: (result) => {
  56. if (result.statusCode >= 200 && result.statusCode < 300) {
  57. resolve(result.data)
  58. } else if (result.statusCode === 401) {
  59. // 清除登录信息
  60. const memberStore = useUserStore()
  61. memberStore.clearUserInfo()
  62. // 提示用户重新登录
  63. uni.navigateTo({
  64. url: '/pages/login/login'
  65. })
  66. reject(result)
  67. } else {
  68. uni.showToast({
  69. title: (result.data).msg || '请求失败',
  70. icon: 'none'
  71. })
  72. reject(result)
  73. }
  74. },
  75. // 2.请求失败
  76. fail: (err) => {
  77. reject(err)
  78. uni.showToast({
  79. title: '网络错误',
  80. icon: 'none'
  81. })
  82. }
  83. })
  84. })
  85. }