previewProxy.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.previewProxy = previewProxy;
  7. const http_1 = __importDefault(require("http"));
  8. const VITE_HOST = "127.0.0.1";
  9. const VITE_PORT = 5199;
  10. // 这些 header 需要从代理响应中剔除(hop-by-hop)
  11. const HOP_BY_HOP = new Set([
  12. "transfer-encoding",
  13. "connection",
  14. "keep-alive",
  15. "proxy-connection",
  16. "proxy-authenticate",
  17. "proxy-authorization",
  18. "te",
  19. "trailers",
  20. "upgrade",
  21. ]);
  22. /**
  23. * 将 /preview/* 请求代理到 Vite dev server。
  24. * 对 HTML 响应自动重写路径,给所有根绝对路径加上 /ads/preview/ 前缀,
  25. * 确保浏览器通过 nginx 正确加载资源。
  26. */
  27. function previewProxy(req, res) {
  28. // Express mount 会剥离 /preview 前缀,req.url 即 Vite 需要的路径
  29. const targetPath = req.url || "/";
  30. console.log(`[preview:proxy] ${req.method} ${targetPath}`);
  31. // 过滤请求 headers(去掉 hop-by-hop,设置正确的 host)
  32. const reqHeaders = {};
  33. for (const [key, value] of Object.entries(req.headers)) {
  34. if (value === undefined)
  35. continue;
  36. const lk = key.toLowerCase();
  37. if (lk === "host")
  38. continue;
  39. if (lk === "connection" || lk === "keep-alive" || lk === "upgrade")
  40. continue;
  41. reqHeaders[key] = Array.isArray(value) ? value.join(", ") : value;
  42. }
  43. reqHeaders["host"] = `${VITE_HOST}:${VITE_PORT}`;
  44. const proxyReq = http_1.default.request({
  45. hostname: VITE_HOST,
  46. port: VITE_PORT,
  47. path: targetPath,
  48. method: req.method,
  49. headers: reqHeaders,
  50. }, (proxyRes) => {
  51. const contentType = (proxyRes.headers["content-type"] || "");
  52. const isHtml = contentType.includes("text/html");
  53. console.log(`[preview:proxy] response ${proxyRes.statusCode} content-type=${contentType} isHtml=${isHtml}`);
  54. // 复制响应 headers(过滤 hop-by-hop)
  55. const resHeaders = {};
  56. for (const [key, value] of Object.entries(proxyRes.headers)) {
  57. if (HOP_BY_HOP.has(key.toLowerCase()))
  58. continue;
  59. if (value !== undefined && value !== null) {
  60. resHeaders[key] = Array.isArray(value) ? value.join(", ") : value;
  61. }
  62. }
  63. res.status(proxyRes.statusCode || 200);
  64. if (isHtml) {
  65. const chunks = [];
  66. proxyRes.on("data", (chunk) => chunks.push(chunk));
  67. proxyRes.on("end", () => {
  68. let html = Buffer.concat(chunks).toString("utf-8");
  69. // 将 src="/..." 和 href="/..." 重写为 /ads/preview/...
  70. // 匹配 root-absolute 路径:以 / 开头,后跟非 / 字符(避免匹配 //)
  71. html = html.replace(/(src|href)="\/([^/][^"]*)"/g, '$1="/ads/preview/$2"');
  72. // 日志:检查重写后的 @vite/client 行
  73. const viteClientMatch = html.match(/src="[^"]*@vite\/client[^"]*"/);
  74. console.log(`[preview:proxy] HTML vite/client: ${viteClientMatch?.[0] || "NOT FOUND"}`);
  75. const body = Buffer.from(html, "utf-8");
  76. resHeaders["content-type"] = "text/html; charset=utf-8";
  77. resHeaders["content-length"] = String(body.length);
  78. res.set(resHeaders);
  79. res.send(body);
  80. });
  81. }
  82. else {
  83. res.set(resHeaders);
  84. proxyRes.pipe(res);
  85. }
  86. });
  87. proxyReq.on("error", (err) => {
  88. console.error(`[preview:proxy] ${err.message}`);
  89. if (!res.headersSent) {
  90. res.status(502).json({ error: "Preview server not available" });
  91. }
  92. });
  93. // POST/PUT/PATCH 请求需要转发 body
  94. if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
  95. req.pipe(proxyReq);
  96. }
  97. else {
  98. proxyReq.end();
  99. }
  100. }
  101. //# sourceMappingURL=previewProxy.js.map