previewProxy.js 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // 复制响应 headers(过滤 hop-by-hop)
  54. const resHeaders = {};
  55. for (const [key, value] of Object.entries(proxyRes.headers)) {
  56. if (HOP_BY_HOP.has(key.toLowerCase()))
  57. continue;
  58. if (value !== undefined && value !== null) {
  59. resHeaders[key] = Array.isArray(value) ? value.join(", ") : value;
  60. }
  61. }
  62. res.status(proxyRes.statusCode || 200);
  63. if (isHtml) {
  64. const chunks = [];
  65. proxyRes.on("data", (chunk) => chunks.push(chunk));
  66. proxyRes.on("end", () => {
  67. let html = Buffer.concat(chunks).toString("utf-8");
  68. // 将 src="/..." 和 href="/..." 重写为 /ads/preview/...
  69. // 匹配 root-absolute 路径:以 / 开头,后跟非 / 字符(避免匹配 //)
  70. html = html.replace(/(src|href)="\/([^/][^"]*)"/g, '$1="/ads/preview/$2"');
  71. const body = Buffer.from(html, "utf-8");
  72. resHeaders["content-type"] = "text/html; charset=utf-8";
  73. resHeaders["content-length"] = String(body.length);
  74. res.set(resHeaders);
  75. res.send(body);
  76. });
  77. }
  78. else {
  79. res.set(resHeaders);
  80. proxyRes.pipe(res);
  81. }
  82. });
  83. proxyReq.on("error", (err) => {
  84. console.error(`[preview:proxy] ${err.message}`);
  85. if (!res.headersSent) {
  86. res.status(502).json({ error: "Preview server not available" });
  87. }
  88. });
  89. // POST/PUT/PATCH 请求需要转发 body
  90. if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
  91. req.pipe(proxyReq);
  92. }
  93. else {
  94. proxyReq.end();
  95. }
  96. }
  97. //# sourceMappingURL=previewProxy.js.map