proxy.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import type { ProxyOptions } from "vite";
  2. type ProxyItem = [string, string];
  3. type ProxyList = ProxyItem[];
  4. type ProxyTargetList = Record<string, ProxyOptions>;
  5. /**
  6. * 创建代理,用于解析 .env.development 代理配置
  7. * @param list
  8. */
  9. export function createProxy(list: ProxyList = []) {
  10. const ret: ProxyTargetList = {};
  11. for (const [prefix, target] of list) {
  12. const httpsRE = /^https:\/\//;
  13. const isHttps = httpsRE.test(target);
  14. // https://github.com/http-party/node-http-proxy#options
  15. ret[prefix] = {
  16. target: target,
  17. changeOrigin: true,
  18. ws: true,
  19. rewrite: path => path.replace(new RegExp(`^${prefix}`), ""),
  20. // https is require secure=false
  21. ...(isHttps ? { secure: false } : {}),
  22. configure: (proxy, options) => {
  23. proxy.on("proxyReq", (proxyReq, req, res, options) => {
  24. console.log("---------------------------------proxyReq----------------------------------");
  25. console.log(proxyReq.path);
  26. });
  27. proxy.on("proxyRes", (proxyRes, req, res) => {
  28. console.log("---------------------------------proxyRes----------------------------------");
  29. console.log("RAW Response from the target", JSON.stringify(proxyRes.headers, null, 2));
  30. });
  31. proxy.on("error", function (err, req, res) {
  32. console.log("error : ", err);
  33. });
  34. }
  35. };
  36. }
  37. return ret;
  38. }