Skip to content

Commit fe678c4

Browse files
authored
fix: update redirect logic for URLs ending with '/'
1 parent 35dd70b commit fe678c4

2 files changed

Lines changed: 29 additions & 2 deletions

File tree

src/utils/getFilenameFromUrl.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ class FilenameError extends Error {
5050
}
5151
}
5252

53-
// TODO fix redirect logic when `/` at the end, like https://github.com/pillarjs/send/blob/master/index.js#L586
5453
/**
5554
* @template {IncomingMessage} Request
5655
* @template {ServerResponse} Response
@@ -120,6 +119,16 @@ function getFilenameFromUrl(context, url) {
120119
);
121120

122121
try {
122+
if (filename[filename.length - 1] === "/") {
123+
if (options.index === false) {
124+
return;
125+
} else if (options.index === "string") {
126+
filename = path.join(filename, options.index);
127+
} else {
128+
filename = path.join(filename, "index.html");
129+
}
130+
}
131+
123132
extra.stats = context.outputFileSystem.statSync(filename);
124133
} catch {
125134
continue;

test/middleware.test.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1736,6 +1736,10 @@ describe.each([
17361736
value: "noextension",
17371737
code: 200,
17381738
},
1739+
{
1740+
value: "noextension/",
1741+
code: 404,
1742+
},
17391743
],
17401744
},
17411745
{
@@ -1780,6 +1784,11 @@ describe.each([
17801784
contentType: "text/plain; charset=utf-8",
17811785
code: 200,
17821786
},
1787+
{
1788+
value: "windows%202.txt/",
1789+
contentType: get404ContentTypeHeader(name),
1790+
code: 404,
1791+
},
17831792
],
17841793
},
17851794
{
@@ -1945,7 +1954,7 @@ describe.each([
19451954

19461955
expect(response.statusCode).toEqual(code);
19471956

1948-
if (data) {
1957+
if (data && code !== 404) {
19491958
expect(response.headers["content-length"]).toEqual(
19501959
String(data.length),
19511960
);
@@ -5187,6 +5196,15 @@ describe.each([
51875196
"text/html; charset=utf-8",
51885197
);
51895198
});
5199+
5200+
it('should return the "404" code for the "GET" request with a non-existent file', async () => {
5201+
const response = await req.get("/default.html/");
5202+
5203+
expect(response.statusCode).toBe(404);
5204+
expect(response.headers["content-type"]).toBe(
5205+
get404ContentTypeHeader(name),
5206+
);
5207+
});
51905208
});
51915209

51925210
describe('should work with "string" value with a custom extension', () => {

0 commit comments

Comments
 (0)