From 7c5efed32d3ee821dd71dcbe37f48d403e2f6589 Mon Sep 17 00:00:00 2001 From: Jan Scheurer Date: Thu, 16 Nov 2023 19:25:50 +0100 Subject: [PATCH] Do not remove content headers for 304 According to [RFC 2616 (HTTP/1.1 spec)](https://datatracker.ietf.org/doc/html/rfc2616#page-54) a `HEAD` request is supposed to return *exactly* the same entity-headers as a `GET` request would but without body. [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2) further specifies that: "Transfer-Encoding MAY be sent in a response to a HEAD request or in a 304 (Not Modified) response" and "A server MAY send a Content-Length header field in a 304 (Not Modified) response to a conditional GET request" --- lib/response.js | 15 +++++++++------ test/res.send.js | 6 ++---- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/lib/response.js b/lib/response.js index fede486c06..17ddf021d1 100644 --- a/lib/response.js +++ b/lib/response.js @@ -209,23 +209,26 @@ res.send = function send(body) { // freshness if (req.fresh) this.statusCode = 304; - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { + // remove content headers for 204 + if (this.statusCode === 204) { this.removeHeader('Content-Type'); this.removeHeader('Content-Length'); this.removeHeader('Transfer-Encoding'); - chunk = ''; } // alter headers for 205 if (this.statusCode === 205) { this.set('Content-Length', '0') this.removeHeader('Transfer-Encoding') - chunk = '' } - if (req.method === 'HEAD') { - // skip body for HEAD + if ( + req.method === 'HEAD' || + this.statusCode === 204 || + this.statusCode === 205 || + this.statusCode === 304 + ) { + // skip body this.end(); } else { // respond diff --git a/test/res.send.js b/test/res.send.js index c92568db6a..1bc6662dd3 100644 --- a/test/res.send.js +++ b/test/res.send.js @@ -300,7 +300,7 @@ describe('res', function(){ }) describe('when .statusCode is 304', function(){ - it('should strip Content-* fields, Transfer-Encoding field, and body', function(done){ + it('should ignore the body', function(done){ var app = express(); app.use(function(req, res){ @@ -309,9 +309,7 @@ describe('res', function(){ request(app) .get('/') - .expect(utils.shouldNotHaveHeader('Content-Type')) - .expect(utils.shouldNotHaveHeader('Content-Length')) - .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) + .expect(utils.shouldNotHaveBody()) .expect(304, '', done); }) })