request.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { getEnvBaseUrl } from '@/utils'
  2. import { platform } from '@/utils/platform'
  3. import { stringifyQuery } from '@/utils/queryString'
  4. export type CustomRequestOptions = UniApp.RequestOptions & {
  5. query?: Record<string, any>
  6. /** 出错时是否隐藏错误提示 */
  7. hideErrorToast?: boolean
  8. } & IUniUploadFileOptions // 添加uni.uploadFile参数类型
  9. // 请求基准地址
  10. const baseUrl = getEnvBaseUrl()
  11. // 拦截器配置
  12. const httpInterceptor = {
  13. // 拦截前触发
  14. invoke(options: CustomRequestOptions) {
  15. // 接口请求支持通过 query 参数配置 queryString
  16. if (options.query) {
  17. const queryStr = stringifyQuery(options.query)
  18. if (options.url.includes('?')) {
  19. options.url += `&${queryStr}`
  20. }
  21. else {
  22. options.url += `?${queryStr}`
  23. }
  24. }
  25. // 非 http 开头需拼接地址
  26. if (!options.url.startsWith('http')) {
  27. // #ifdef H5
  28. // console.log(__VITE_APP_PROXY__)
  29. if (JSON.parse(__VITE_APP_PROXY__)) {
  30. // 自动拼接代理前缀
  31. options.url = import.meta.env.VITE_APP_PROXY_PREFIX + options.url
  32. }
  33. else {
  34. options.url = baseUrl + options.url
  35. }
  36. // #endif
  37. // 非H5正常拼接
  38. // #ifndef H5
  39. options.url = baseUrl + options.url
  40. // #endif
  41. // TIPS: 如果需要对接多个后端服务,也可以在这里处理,拼接成所需要的地址
  42. }
  43. // 1. 请求超时
  44. options.timeout = 10000 // 10s
  45. // 2. (可选)添加小程序端请求头标识
  46. options.header = {
  47. platform, // 可选,与 uniapp 定义的平台一致,告诉后台来源
  48. ...options.header,
  49. }
  50. // 判断是否为登录接口
  51. const isLoginApi = options.url?.includes('/login') || options.url?.includes('/register')
  52. // 如果不是登录接口,添加 token 请求头
  53. if (!isLoginApi) {
  54. const token = uni.getStorageSync('token')
  55. if (token) {
  56. options.header.Token = token
  57. }
  58. }
  59. },
  60. }
  61. export const requestInterceptor = {
  62. install() {
  63. // 拦截 request 请求
  64. uni.addInterceptor('request', httpInterceptor)
  65. // 拦截 uploadFile 文件上传
  66. uni.addInterceptor('uploadFile', httpInterceptor)
  67. },
  68. }