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.

90 lines
3.5 KiB

4 weeks ago
  1. import { useUserStore } from "../stores/modules/userInfo"
  2. const baseURL = "https://hwjb.homilychart.com"
  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. // 'contentType': 'application/json',
  33. 'version': '1',
  34. 'client': client
  35. }
  36. //4 添加token,优先用store,没有则回退到body中的token,保持与Apifox一致
  37. const memberStore = useUserStore()
  38. // const token = memberStore.userInfo?.token || options.data?.token
  39. const token = '790750702588f1ea79f24dc56ccd5d8a'
  40. if (token) {
  41. options.header.token = token
  42. }
  43. // 避免误用 Authorization 头,后端要求的是 token 头
  44. // if (options.header.Authorization) delete options.header.Authorization
  45. return options
  46. }
  47. }
  48. // 添加拦截器
  49. uni.addInterceptor('request', httpInterceptor)
  50. uni.addInterceptor('uploadFile', httpInterceptor)
  51. // 添加请求函数
  52. export const http = (options) => {
  53. return new Promise((resolve, reject) => {
  54. uni.request({
  55. ...options,
  56. // 1.请求成功
  57. success: (result) => {
  58. if (result.statusCode >= 200 && result.statusCode < 300) {
  59. resolve(result.data)
  60. } else if (result.statusCode === 401) {
  61. // 清除登录信息
  62. const memberStore = useUserStore()
  63. memberStore.clearUserInfo()
  64. // 提示用户重新登录
  65. uni.navigateTo({
  66. url: '/pages/login/login'
  67. })
  68. reject(result)
  69. } else {
  70. uni.showToast({
  71. title: (result.data).msg || '请求失败',
  72. icon: 'none'
  73. })
  74. reject(result)
  75. }
  76. },
  77. // 2.请求失败
  78. fail: (err) => {
  79. reject(err)
  80. uni.showToast({
  81. title: '网络错误',
  82. icon: 'none'
  83. })
  84. }
  85. })
  86. })
  87. }