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.

92 lines
3.6 KiB

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