fix(context): handle HEAD requests (#1034)
This commit is contained in:
+19
-2
@@ -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;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user