From 9b94b834a90b0551dd6191bceb40eac3ee630dcc Mon Sep 17 00:00:00 2001 From: linhongkuan Date: Wed, 24 Jun 2026 21:57:42 +0800 Subject: [PATCH] fix(res.format): ignore inherited default handler --- lib/response.js | 3 ++- test/res.format.js | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/lib/response.js b/lib/response.js index b4755a5c060..9109efa3972 100644 --- a/lib/response.js +++ b/lib/response.js @@ -571,6 +571,7 @@ res.type = function contentType(type) { res.format = function(obj){ var req = this.req; var next = req.next; + var hasDefault = Object.prototype.hasOwnProperty.call(obj, 'default'); var keys = Object.keys(obj) .filter(function (v) { return v !== 'default' }) @@ -584,7 +585,7 @@ res.format = function(obj){ if (key) { this.set('Content-Type', normalizeType(key).value); obj[key](req, this, next); - } else if (obj.default) { + } else if (hasDefault && obj.default) { obj.default(req, this, next) } else { next(createError(406, { diff --git a/test/res.format.js b/test/res.format.js index 0d770d57651..660c4f56eea 100644 --- a/test/res.format.js +++ b/test/res.format.js @@ -149,6 +149,33 @@ describe('res', function(){ .expect('json') .end(done) }) + + it('should ignore inherited default callbacks', function (done) { + var app = express() + var formats = Object.create({ + default: function () { + throw new Error('should not be called') + } + }) + + formats.text = function () { + throw new Error('should not be called') + } + + app.use(function (req, res) { + res.format(formats) + }) + + app.use(function (err, req, res, next) { + res.status(err.status) + res.send('Supports: ' + err.types.join(', ')) + }) + + request(app) + .get('/') + .set('Accept', 'application/json') + .expect(406, 'Supports: text/plain', done) + }) }) describe('in router', function(){