Skip to content

Commit 434f1e5

Browse files
qianmao1989claude
andcommitted
fix: suppress response body for HEAD requests
HEAD responses must have identical headers to GET but no body (RFC 9110 §9.3.2). uWS is low-level and doesn't strip bodies for HEAD automatically. - In endResponse(), check req.method === 'HEAD' and use endWithoutBody() or end() without body when method is HEAD - Add unit tests for HEAD request handling Fixes #151 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 94152e5 commit 434f1e5

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
@@ -1390,6 +1390,15 @@ export class UwsResponse extends Writable {
13901390
}
13911391

13921392
private endResponse(body: string | Buffer | undefined): void {
1393+
// HEAD responses must have identical headers to GET but no body (RFC 9110 §9.3.2)
1394+
if (this.req?.method === 'HEAD') {
1395+
if (this.contentLengthTotal !== undefined) {
1396+
this.uwsRes.endWithoutBody(this.contentLengthTotal);
1397+
} else {
1398+
this.uwsRes.end();
1399+
}
1400+
return;
1401+
}
13931402
if (body !== undefined) {
13941403
this.uwsRes.end(body);
13951404
return;

0 commit comments

Comments
 (0)