Skip to content

Commit

Permalink
Do not remove content headers for 304
Browse files Browse the repository at this point in the history
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"
  • Loading branch information
LJ1102 authored and Jan Scheurer committed Nov 17, 2023
1 parent 2a00da2 commit 7c5efed
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
15 changes: 9 additions & 6 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 2 additions & 4 deletions test/res.send.js
Original file line number Diff line number Diff line change
Expand Up @@ -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){
Expand All @@ -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);
})
})
Expand Down

0 comments on commit 7c5efed

Please sign in to comment.