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.

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