fix(res): remove magic from res.set() Content-Type - #7430
Conversation
kilisamemarisaaa
left a comment
There was a problem hiding this comment.
Removing the Content-Type expansion here also changes res.format(). Unlike res.json() and res.jsonp(), its internal call still uses:
this.set('Content-Type', normalizeType(key).value)I reproduced this with a formatter that ends the response directly:
res.format({
'text/plain': () => res.end('ok')
})On the current base (023767fe) the response is text/plain; charset=utf-8; on this head (2151c645) it is only text/plain. The existing res.format suite still passes 38/38 because its handlers use res.send(), which adds the charset later and masks the regression.
Could res.format() be migrated to the explicit type API as well, with a regression test whose formatter uses res.end()?
|
Thanks for the great catch @kilisamemarisaaa! I've updated I also added the regression test in \ est/res.format.js\ asserting that a formatter calling Pushed in commit \5ab54bc5\ — all format and response tests are passing cleanly. |
Problem
Currently,
res.set()contains unexpected magic when setting theContent-Typeheader. If a given content-type string does not contain a/(e.g., shorthand like'json'or invalid input),res.set()attempts a MIME type lookup viamime.contentType(). This mutates user input unexpectedly and causes a known bug (Issue #7034), where unrecognized types returnfalsefrommime.contentType()and the header gets coercively set to the literal string"false".Solution
This PR removes the MIME type lookup logic from
res.set()completely, keepingres.set()strictly for assigning header values as provided, which resolves unexpected mutations. The intended way to set a content type with MIME type expansion remainsres.type()(which already exists for this exact purpose).By migrating internal dependencies (
res.jsonandres.jsonp) to useres.type()instead ofres.set(), we maintain backward compatibility for built-in response types (such as automatically appendingcharset=utf-8to JSON responses) while fulfilling the goal of makingres.set()predictable.Changes Made
lib/response.js:res.set(): Removed themime.contentType()assignment block and the associated obsolete JSDoc comments. Kept the validation that preventsContent-Typefrom being set to an Array.res.json(): Refactoredthis.set('Content-Type', ...)tothis.type('json')to preservecharset=utf-8expansion.res.jsonp(): Refactoredthis.set('Content-Type', ...)tothis.type('json')andthis.type('text/javascript')to maintain expansion behavior for JSON/JSONP responses.test/res.send.js:res.set('Content-Type', 'text/plain')was used, expecting exactly'text/plain'rather than'text/plain; charset=utf-8'.Testing
res.set('Content-Type', 'some-custom-type');Content-Type: false.Content-Type: some-custom-type.res.type('json')andres.json({})still properly resolve toapplication/json; charset=utf-8.npm test(all 1260 tests passed locally).Fixes #7145
Fixes #7034