previewProxy.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import { Request, Response } from "express";
  2. import http from "http";
  3. const VITE_HOST = "127.0.0.1";
  4. const VITE_PORT = 5199;
  5. // 这些 header 需要从代理响应中剔除(hop-by-hop)
  6. const HOP_BY_HOP = new Set([
  7. "transfer-encoding",
  8. "connection",
  9. "keep-alive",
  10. "proxy-connection",
  11. "proxy-authenticate",
  12. "proxy-authorization",
  13. "te",
  14. "trailers",
  15. "upgrade",
  16. ]);
  17. /**
  18. * 将 /preview/* 请求代理到 Vite dev server。
  19. * 对 HTML 响应自动重写路径,给所有根绝对路径加上 /ads/preview/ 前缀,
  20. * 确保浏览器通过 nginx 正确加载资源。
  21. */
  22. export function previewProxy(req: Request, res: Response): void {
  23. // Express mount 会剥离 /preview 前缀,req.url 即 Vite 需要的路径
  24. const targetPath = req.url || "/";
  25. console.log(`[preview:proxy] ${req.method} ${targetPath}`);
  26. // 过滤请求 headers(去掉 hop-by-hop、条件缓存头,设置正确的 host)
  27. const reqHeaders: Record<string, string> = {};
  28. for (const [key, value] of Object.entries(req.headers)) {
  29. if (value === undefined) continue;
  30. const lk = key.toLowerCase();
  31. if (lk === "host") continue;
  32. if (lk === "connection" || lk === "keep-alive" || lk === "upgrade") continue;
  33. // 强制完整响应,避免 304 缓存导致 HTML 无法被重写
  34. if (lk === "if-none-match" || lk === "if-modified-since" || lk === "cache-control") continue;
  35. reqHeaders[key] = Array.isArray(value) ? value.join(", ") : value;
  36. }
  37. reqHeaders["host"] = `${VITE_HOST}:${VITE_PORT}`;
  38. reqHeaders["cache-control"] = "no-cache";
  39. const proxyReq = http.request(
  40. {
  41. hostname: VITE_HOST,
  42. port: VITE_PORT,
  43. path: targetPath,
  44. method: req.method,
  45. headers: reqHeaders,
  46. },
  47. (proxyRes) => {
  48. const contentType = (proxyRes.headers["content-type"] || "") as string;
  49. const isText = contentType.includes("text/html") ||
  50. contentType.includes("text/javascript") ||
  51. contentType.includes("application/javascript");
  52. console.log(`[preview:proxy] response ${proxyRes.statusCode} content-type=${contentType} isText=${isText}`);
  53. // 复制响应 headers(过滤 hop-by-hop)
  54. const resHeaders: Record<string, string> = {};
  55. for (const [key, value] of Object.entries(proxyRes.headers)) {
  56. if (HOP_BY_HOP.has(key.toLowerCase())) continue;
  57. if (value !== undefined && value !== null) {
  58. resHeaders[key] = Array.isArray(value) ? value.join(", ") : value;
  59. }
  60. }
  61. res.status(proxyRes.statusCode || 200);
  62. if (isText) {
  63. const chunks: Buffer[] = [];
  64. proxyRes.on("data", (chunk: Buffer) => chunks.push(chunk));
  65. proxyRes.on("end", () => {
  66. let body = Buffer.concat(chunks).toString("utf-8");
  67. // 重写 HTML (src="/...", href="/...") 和 JS (from "/...", import "/...")
  68. // 为 /ads/preview/...(跳过已有前缀的,支持单双引号)
  69. body = body.replace(
  70. /((?:src|href)=["']|(?:from|import)\s*["'])\/(?!ads\/preview\/)([^"']+)(["'])/g,
  71. '$1/ads/preview/$2$3',
  72. );
  73. // 日志
  74. if (contentType.includes("text/html")) {
  75. const viteClientMatch = body.match(/src="[^"]*@vite\/client[^"]*"/);
  76. console.log(`[preview:proxy] HTML vite/client: ${viteClientMatch?.[0] || "NOT FOUND"}`);
  77. }
  78. resHeaders["content-type"] = contentType.includes("text/html")
  79. ? "text/html; charset=utf-8"
  80. : contentType;
  81. resHeaders["content-length"] = String(Buffer.byteLength(body, "utf-8"));
  82. res.set(resHeaders);
  83. res.send(body);
  84. });
  85. } else {
  86. res.set(resHeaders);
  87. proxyRes.pipe(res);
  88. }
  89. },
  90. );
  91. proxyReq.on("error", (err) => {
  92. console.error(`[preview:proxy] ${err.message}`);
  93. if (!res.headersSent) {
  94. res.status(502).json({ error: "Preview server not available" });
  95. }
  96. });
  97. // POST/PUT/PATCH 请求需要转发 body
  98. if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
  99. req.pipe(proxyReq);
  100. } else {
  101. proxyReq.end();
  102. }
  103. }