Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: enhance req.acceptsCharsets method #6088

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,17 +147,34 @@ req.acceptsEncodings = function(){
};

/**
* Check if the given `charset`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
* Checks if the specified `charset`s are acceptable based on the request's `Accept-Charset` header.
* Returns the best matching charset or an array of acceptable charsets.
*
* @param {String} ...charset
* @return {String|Array}
* The `charset` argument(s) can be:
* - A single charset string (e.g., "utf-8")
* - Multiple charset strings as arguments (e.g., `"utf-8", "iso-8859-1"`)
* - A comma-delimited list of charsets (e.g., `"utf-8, iso-8859-1"`)
*
* Examples:
*
* // Accept-Charset: utf-8, iso-8859-1
* req.acceptsCharsets('utf-8');
* // => "utf-8"
*
* req.acceptsCharsets('utf-8', 'iso-8859-1');
* // => "utf-8"
*
* req.acceptsCharsets('utf-8, utf-16');
* // => "utf-8"
*
* @param {...String} charsets - The charset(s) to check against the `Accept-Charset` header.
* @return {String|Array} - The best matching charset, or an array of acceptable charsets.
* @public
*/

req.acceptsCharsets = function(){
var accept = accepts(this);
return accept.charsets.apply(accept, arguments);
req.acceptsCharsets = function(...charsets) {
const accept = accepts(this);
return accept.charsets(...charsets);
};

/**
Expand Down
13 changes: 13 additions & 0 deletions test/req.acceptsCharsets.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ describe('req', function(){
.set('Accept-Charset', 'foo, bar')
.expect('no', done);
})

it('should return the best matching charset from multiple inputs', function (done) {
var app = express();

app.use(function(req, res, next){
res.end(req.acceptsCharsets('utf-8', 'iso-8859-1') || 'none');
});

request(app)
.get('/')
.set('Accept-Charset', 'iso-8859-1, utf-8')
.expect('iso-8859-1', done);
})
})
})
})
Loading