proxy.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Used to parse the .env.development proxy configuration
  3. */
  4. import type { ProxyOptions } from 'vite'
  5. type ProxyItem = [string, string]
  6. type ProxyList = ProxyItem[]
  7. type ProxyTargetList = Record<string, ProxyOptions & { rewrite: (path: string) => string }>
  8. const httpsRE = /^https:\/\//
  9. /**
  10. * Generate proxy
  11. * @param list
  12. */
  13. export function createProxy(list: ProxyList = []) {
  14. const ret: ProxyTargetList = {}
  15. for (const [prefix, target] of list) {
  16. const isHttps = httpsRE.test(target)
  17. // https://github.com/http-party/node-http-proxy#options
  18. ret[prefix] = {
  19. target,
  20. changeOrigin: true,
  21. ws: true,
  22. rewrite: path => path.replace(new RegExp(`^${prefix}`), ''),
  23. // https is require secure=false
  24. // 如果您secure="true"只允许来自 HTTPS 的请求,则secure="false"意味着允许来自 HTTP 和 HTTPS 的请求。
  25. ...(isHttps ? { secure: false } : {}),
  26. }
  27. }
  28. return ret
  29. // ret
  30. // {
  31. // '/test/api': {
  32. // target: 'http://localhost:3080/test/api',
  33. // changeOrigin: true,
  34. // ws: true,
  35. // rewrite: (path) => path.replace(new RegExp(/^\/test/api/), ''),
  36. // },
  37. // '/upload': {
  38. // target: 'http://localhost:8001/upload',
  39. // changeOrigin: true,
  40. // ws: true,
  41. // rewrite: (path) => path.replace(new RegExp(/^\/upload/), ''),
  42. // }
  43. // }
  44. }