fix(context): handle HEAD requests (#1034)

This commit is contained in:
hashrock
2023-02-27 16:37:40 -04:00
committed by GitHub
parent 8daa4849cf
commit f04716df5c
2 changed files with 42 additions and 2 deletions
+19 -2
View File
@@ -312,7 +312,7 @@ export class ServerContext {
handler(): RequestHandler {
const inner = rutt.router<RouterState>(...this.#handlers());
const withMiddlewares = this.#composeMiddlewares(this.#middlewares);
return function handler(req: Request, connInfo: ConnInfo) {
return async function handler(req: Request, connInfo: ConnInfo) {
// Redirect requests that end with a trailing slash
// to their non-trailing slash counterpart.
// Ex: /about/ -> /about
@@ -321,7 +321,24 @@ export class ServerContext {
url.pathname = url.pathname.slice(0, -1);
return Response.redirect(url.href, Status.TemporaryRedirect);
}
return withMiddlewares(req, connInfo, inner);
// HEAD requests should be handled as GET requests
// but without the body.
const originalMethod = req.method;
// Internally, HEAD is handled in the same way as GET.
if (req.method === "HEAD") {
req = new Request(req.url, { method: "GET", headers: req.headers });
}
const res = await withMiddlewares(req, connInfo, inner);
if (originalMethod === "HEAD") {
res.body?.cancel();
return new Response(null, {
headers: res.headers,
status: res.status,
statusText: res.statusText,
});
}
return res;
};
}
+23
View File
@@ -254,6 +254,29 @@ Deno.test("static file - by file path", async () => {
assertEquals(resp3.headers.get("content-type"), "text/plain");
});
Deno.test("HEAD request", async () => {
// Static file
const resp = await router(
new Request("https://fresh.deno.dev/foo.txt", {
method: "HEAD",
}),
);
assertEquals(resp.status, Status.OK);
const body = await resp.text();
assertEquals(body, "");
// route
const resp2 = await router(
new Request("https://fresh.deno.dev/books/123", {
method: "HEAD",
}),
);
assert(resp2);
assertEquals(resp2.status, Status.OK);
const body2 = await resp2.text();
assertEquals(body2, "");
});
Deno.test("static file - by 'hashed' path", async () => {
// Check that the file path have the BUILD_ID
const resp = await router(