Skip to content

Commit 69202bb

Browse files
Merge pull request #154 from qianmao1989/fix/head-response-body
fix: suppress response body for HEAD requests
2 parents 1991cb6 + 434f1e5 commit 69202bb

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

src/http/core/response.spec.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,41 @@ describe('UwsResponse', () => {
565565
});
566566
});
567567

568+
describe('HEAD request handling', () => {
569+
it('should suppress body for HEAD request with content-length', () => {
570+
res = createResponse();
571+
const mockReq = { method: 'HEAD' } as any;
572+
res.bindRequest(mockReq);
573+
574+
res.setHeader('content-length', '1024').send('Hello');
575+
576+
expect(mockUwsRes.endWithoutBody).toHaveBeenCalledWith(1024);
577+
expect(mockUwsRes.end).not.toHaveBeenCalled();
578+
});
579+
580+
it('should suppress body for HEAD request without content-length', () => {
581+
res = createResponse();
582+
const mockReq = { method: 'HEAD' } as any;
583+
res.bindRequest(mockReq);
584+
585+
res.send('Hello');
586+
587+
expect(mockUwsRes.end).toHaveBeenCalledWith();
588+
expect(mockUwsRes.endWithoutBody).not.toHaveBeenCalled();
589+
});
590+
591+
it('should send body normally for GET request', () => {
592+
res = createResponse();
593+
const mockReq = { method: 'GET' } as any;
594+
res.bindRequest(mockReq);
595+
596+
res.send('Hello');
597+
598+
expect(mockUwsRes.end).toHaveBeenCalledWith('Hello');
599+
expect(mockUwsRes.endWithoutBody).not.toHaveBeenCalled();
600+
});
601+
});
602+
568603
describe('json()', () => {
569604
beforeEach(() => {
570605
res = createResponse();

src/http/core/response.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1433,6 +1433,15 @@ export class UwsResponse extends Writable {
14331433
}
14341434

14351435
private endResponse(body: string | Buffer | undefined): void {
1436+
// HEAD responses must have identical headers to GET but no body (RFC 9110 §9.3.2)
1437+
if (this.req?.method === 'HEAD') {
1438+
if (this.contentLengthTotal !== undefined) {
1439+
this.uwsRes.endWithoutBody(this.contentLengthTotal);
1440+
} else {
1441+
this.uwsRes.end();
1442+
}
1443+
return;
1444+
}
14361445
if (body !== undefined) {
14371446
this.uwsRes.end(body);
14381447
return;

0 commit comments

Comments
 (0)