Skip to content

Commit 6cd404e

Browse files
Abdel-Monaam-AouiniMonaam Aouinibjohansebas
authored
fix: enhance req.acceptsCharsets method (#6088)
* fix: enhance req.acceptsCharsets method * Update req.acceptsCharsets.js --------- Co-authored-by: Monaam Aouini <[email protected]> Co-authored-by: Sebastian Beltran <[email protected]>
1 parent 3e81873 commit 6cd404e

File tree

2 files changed

+37
-7
lines changed

2 files changed

+37
-7
lines changed

lib/request.js

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,17 +147,34 @@ req.acceptsEncodings = function(){
147147
};
148148

149149
/**
150-
* Check if the given `charset`s are acceptable,
151-
* otherwise you should respond with 406 "Not Acceptable".
150+
* Checks if the specified `charset`s are acceptable based on the request's `Accept-Charset` header.
151+
* Returns the best matching charset or an array of acceptable charsets.
152152
*
153-
* @param {String} ...charset
154-
* @return {String|Array}
153+
* The `charset` argument(s) can be:
154+
* - A single charset string (e.g., "utf-8")
155+
* - Multiple charset strings as arguments (e.g., `"utf-8", "iso-8859-1"`)
156+
* - A comma-delimited list of charsets (e.g., `"utf-8, iso-8859-1"`)
157+
*
158+
* Examples:
159+
*
160+
* // Accept-Charset: utf-8, iso-8859-1
161+
* req.acceptsCharsets('utf-8');
162+
* // => "utf-8"
163+
*
164+
* req.acceptsCharsets('utf-8', 'iso-8859-1');
165+
* // => "utf-8"
166+
*
167+
* req.acceptsCharsets('utf-8, utf-16');
168+
* // => "utf-8"
169+
*
170+
* @param {...String} charsets - The charset(s) to check against the `Accept-Charset` header.
171+
* @return {String|Array} - The best matching charset, or an array of acceptable charsets.
155172
* @public
156173
*/
157174

158-
req.acceptsCharsets = function(){
159-
var accept = accepts(this);
160-
return accept.charsets.apply(accept, arguments);
175+
req.acceptsCharsets = function(...charsets) {
176+
const accept = accepts(this);
177+
return accept.charsets(...charsets);
161178
};
162179

163180
/**

test/req.acceptsCharsets.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,19 @@ describe('req', function(){
4545
.set('Accept-Charset', 'foo, bar')
4646
.expect('no', done);
4747
})
48+
49+
it('should return the best matching charset from multiple inputs', function (done) {
50+
var app = express();
51+
52+
app.use(function(req, res, next){
53+
res.end(req.acceptsCharsets('utf-8', 'iso-8859-1'));
54+
});
55+
56+
request(app)
57+
.get('/')
58+
.set('Accept-Charset', 'iso-8859-1, utf-8')
59+
.expect('iso-8859-1', done);
60+
})
4861
})
4962
})
5063
})

0 commit comments

Comments
 (0)