viteProxy.config.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import type { ProxyOptions } from 'vite'
  2. type ProxyItem = [string, string]
  3. type ProxyList = ProxyItem[]
  4. type ProxyTargetList = Record<string, ProxyOptions>
  5. const proxyList: ProxyList = [['/api', 'http://localhost:8301/api']]
  6. /**
  7. * 创建代理配置
  8. * @param base 项目根路径,必须以“/”结尾,例如“/base/”
  9. * @param debug 是否开启调试模式,打印请求信息
  10. */
  11. export function createProxy(base?: string, debug?: boolean) {
  12. const ret: ProxyTargetList = {}
  13. for (const [prefix, target] of proxyList) {
  14. const isHttps = target.startsWith('https://')
  15. const completePrefix = base ? base.replace(/\/+$/, '') + prefix : prefix
  16. // https://github.com/http-party/node-http-proxy#options
  17. ret[completePrefix] = {
  18. target: target,
  19. changeOrigin: true,
  20. ws: true,
  21. rewrite: (path) => path.replace(new RegExp(`^${completePrefix}`), ''),
  22. // https is require secure=false
  23. ...(isHttps ? { secure: false } : {}),
  24. configure: debug
  25. ? (proxy, options) => {
  26. proxy.on('proxyReq', (proxyReq, req, res, options) => {
  27. console.log(
  28. '---------------------------------proxyReq----------------------------------',
  29. )
  30. console.log(proxyReq.path)
  31. })
  32. proxy.on('proxyRes', (proxyRes, req, res) => {
  33. console.log(
  34. '---------------------------------proxyRes----------------------------------',
  35. )
  36. console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, null, 2))
  37. })
  38. proxy.on('error', function (err, req, res) {
  39. console.log('error : ', err)
  40. })
  41. }
  42. : undefined,
  43. }
  44. }
  45. return ret
  46. }