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.

91 lines
3.6 KiB

  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. options.header.token = 'dccec0b65a94f498b8183a17589ab16e'
  40. const token = 'dccec0b65a94f498b8183a17589ab16e'
  41. if (token) {
  42. options.header.token = token
  43. }
  44. // 避免误用 Authorization 头,后端要求的是 token 头
  45. // if (options.header.Authorization) delete options.header.Authorization
  46. return options
  47. }
  48. }
  49. // 添加拦截器
  50. uni.addInterceptor('request', httpInterceptor)
  51. uni.addInterceptor('uploadFile', httpInterceptor)
  52. // 添加请求函数
  53. export const http = (options) => {
  54. return new Promise((resolve, reject) => {
  55. uni.request({
  56. ...options,
  57. // 1.请求成功
  58. success: (result) => {
  59. if (result.statusCode >= 200 && result.statusCode < 300) {
  60. resolve(result.data)
  61. } else if (result.statusCode === 401) {
  62. // 清除登录信息
  63. const memberStore = useUserStore()
  64. memberStore.clearUserInfo()
  65. // 提示用户重新登录
  66. uni.navigateTo({
  67. url: '/pages/login/login'
  68. })
  69. reject(result)
  70. } else {
  71. uni.showToast({
  72. title: (result.data).msg || '请求失败',
  73. icon: 'none'
  74. })
  75. reject(result)
  76. }
  77. },
  78. // 2.请求失败
  79. fail: (err) => {
  80. reject(err)
  81. uni.showToast({
  82. title: '网络错误',
  83. icon: 'none'
  84. })
  85. }
  86. })
  87. })
  88. }