From e48d23c57da5eb01e5eab3d775ac646f094c043c Mon Sep 17 00:00:00 2001 From: Raashish Aggarwal <94279692+raashish1601@users.noreply.github.com> Date: Fri, 27 Mar 2026 16:45:51 +0530 Subject: [PATCH] Fix fallback for unknown Content-Type values --- lib/response.js | 2 +- lib/utils.js | 9 +++++++-- test/res.set.js | 28 ++++++++++++++++++++++++++++ test/utils.js | 4 ++++ 4 files changed, 40 insertions(+), 3 deletions(-) diff --git a/lib/response.js b/lib/response.js index f965e539dd2..bc2bc6fb438 100644 --- a/lib/response.js +++ b/lib/response.js @@ -673,7 +673,7 @@ res.header = function header(field, val) { if (Array.isArray(value)) { throw new TypeError('Content-Type cannot be set to an Array'); } - value = mime.contentType(value) + value = mime.contentType(value) || value } this.setHeader(field, value); diff --git a/lib/utils.js b/lib/utils.js index 4f21e7ef1e3..2a89e07d3c0 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -227,8 +227,13 @@ exports.setCharset = function setCharset(type, charset) { return type; } - // parse type - var parsed = contentType.parse(type); + // preserve unparseable values instead of throwing when callers set + // a non-standard Content-Type manually. + try { + var parsed = contentType.parse(type); + } catch { + return type; + } // set charset parsed.parameters.charset = charset; diff --git a/test/res.set.js b/test/res.set.js index 04511c1c95f..b41605676f0 100644 --- a/test/res.set.js +++ b/test/res.set.js @@ -31,6 +31,34 @@ describe('res', function(){ .expect('X-Number', '123') .expect(200, 'string', done); }) + + it('should preserve unknown Content-Type values', function (done) { + var app = express(); + + app.use(function (req, res) { + res.set('Content-Type', 'some-custom-type'); + res.end('hello'); + }); + + request(app) + .get('/') + .expect('Content-Type', 'some-custom-type') + .expect(200, 'hello', done); + }) + + it('should preserve unknown Content-Type values when sending strings', function (done) { + var app = express(); + + app.use(function (req, res) { + res.set('Content-Type', 'some-custom-type'); + res.send('hello'); + }); + + request(app) + .get('/') + .expect('Content-Type', 'some-custom-type') + .expect(200, 'hello', done); + }) }) describe('.set(field, values)', function(){ diff --git a/test/utils.js b/test/utils.js index d1174d014cf..be0c3db2719 100644 --- a/test/utils.js +++ b/test/utils.js @@ -65,6 +65,10 @@ describe('utils.setCharset(type, charset)', function () { it('should override charset', function () { assert.strictEqual(utils.setCharset('text/html; charset=iso-8859-1', 'utf-8'), 'text/html; charset=utf-8'); }); + + it('should preserve unparseable types', function () { + assert.strictEqual(utils.setCharset('some-custom-type', 'utf-8'), 'some-custom-type'); + }); }); describe('utils.wetag(body, encoding)', function(){