previewProxy.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. // 过滤请求 headers(去掉 hop-by-hop,设置正确的 host)
  31. const reqHeaders = {};
  32. for (const [key, value] of Object.entries(req.headers)) {
  33. if (value === undefined)
  34. continue;
  35. const lk = key.toLowerCase();
  36. if (lk === "host")
  37. continue;
  38. if (lk === "connection" || lk === "keep-alive" || lk === "upgrade")
  39. continue;
  40. reqHeaders[key] = Array.isArray(value) ? value.join(", ") : value;
  41. }
  42. reqHeaders["host"] = `${VITE_HOST}:${VITE_PORT}`;
  43. const proxyReq = http_1.default.request({
  44. hostname: VITE_HOST,
  45. port: VITE_PORT,
  46. path: targetPath,
  47. method: req.method,
  48. headers: reqHeaders,
  49. }, (proxyRes) => {
  50. const contentType = (proxyRes.headers["content-type"] || "");
  51. const isHtml = contentType.includes("text/html");
  52. // 复制响应 headers(过滤 hop-by-hop)
  53. const resHeaders = {};
  54. for (const [key, value] of Object.entries(proxyRes.headers)) {
  55. if (HOP_BY_HOP.has(key.toLowerCase()))
  56. 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 (isHtml) {
  63. const chunks = [];
  64. proxyRes.on("data", (chunk) => chunks.push(chunk));
  65. proxyRes.on("end", () => {
  66. let html = Buffer.concat(chunks).toString("utf-8");
  67. // 将 src="/..." 和 href="/..." 重写为 /ads/preview/...
  68. // 匹配 root-absolute 路径:以 / 开头,后跟非 / 字符(避免匹配 //)
  69. html = html.replace(/(src|href)="\/([^/][^"]*)"/g, '$1="/ads/preview/$2"');
  70. const body = Buffer.from(html, "utf-8");
  71. resHeaders["content-type"] = "text/html; charset=utf-8";
  72. resHeaders["content-length"] = String(body.length);
  73. res.set(resHeaders);
  74. res.send(body);
  75. });
  76. }
  77. else {
  78. res.set(resHeaders);
  79. proxyRes.pipe(res);
  80. }
  81. });
  82. proxyReq.on("error", (err) => {
  83. console.error(`[preview:proxy] ${err.message}`);
  84. if (!res.headersSent) {
  85. res.status(502).json({ error: "Preview server not available" });
  86. }
  87. });
  88. // POST/PUT/PATCH 请求需要转发 body
  89. if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
  90. req.pipe(proxyReq);
  91. }
  92. else {
  93. proxyReq.end();
  94. }
  95. }
  96. //# sourceMappingURL=previewProxy.js.map