Skip to content

Commit 98b6df4

Browse files
authored
Merge pull request #24 from sapphi-red/support-empty-req-url
feat: support empty `req.url`
2 parents c3da184 + e7acb6e commit 98b6df4

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

lib/http-proxy/common.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,9 @@ function hasPort(host: string): boolean {
268268
}
269269

270270
function getPath(url?: string): string {
271+
if (url === '' || url?.startsWith('?')) {
272+
return url
273+
}
271274
const u = toURL(url);
272275
return `${u.pathname ?? ""}${u.search ?? ""}`;
273276
}

lib/test/http/empty-req-url.test.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import express from "express";
2+
import getPort from "../get-port";
3+
import ProxyServer, { createServer } from "../..";
4+
import http from "node:http";
5+
6+
describe("test empty req.url", () => {
7+
let port: number, server: http.Server;
8+
9+
it("create a simple http server", async () => {
10+
port = await getPort();
11+
const app = express();
12+
13+
app.get("/test", (req, res, next) => {
14+
if (req.path !== "/test") return next();
15+
res.send("Test Page!: " + JSON.stringify(req.query));
16+
});
17+
18+
server = app.listen(port);
19+
});
20+
21+
let proxy: ProxyServer, httpServer: http.Server;
22+
let proxyPort: number;
23+
it("create a proxy server", async () => {
24+
proxy = createServer();
25+
proxy.on("error", (err, _req, res) => {
26+
console.error("Proxy error:", err);
27+
res.end("Something went wrong.");
28+
});
29+
httpServer = http.createServer((req, res) => {
30+
req.url = '' + new URL(`http://example.com${req.url}`).search;
31+
proxy.web(req, res, { target: `http://localhost:${port}/test` });
32+
});
33+
34+
proxyPort = await getPort();
35+
httpServer.listen(proxyPort);
36+
});
37+
38+
const getProxy = async (url: string) => {
39+
return await (await fetch(`http://localhost:${proxyPort}${url}`)).text();
40+
};
41+
42+
it("get using the proxy", async () => {
43+
expect(await getProxy("")).toBe("Test Page!: {}");
44+
expect(await getProxy("?foo")).toBe("Test Page!: {\"foo\":\"\"}");
45+
expect(await getProxy("?foo=bar")).toBe("Test Page!: {\"foo\":\"bar\"}");
46+
});
47+
48+
it("clean up", () => {
49+
server.close();
50+
httpServer.close();
51+
});
52+
});

lib/test/lib/http-proxy-common.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,7 @@ describe("#setupOutgoing", () => {
487487
const outgoing: any = {};
488488
setupOutgoing(outgoing, { target: { pathname: "" } }, { url: "" });
489489

490-
expect(outgoing.path).toEqual("/");
490+
expect(outgoing.path).toEqual("");
491491
});
492492
});
493493

0 commit comments

Comments
 (0)