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;
};
}