From 7ae9c3e1099688ada21411a350d2b50dae629388 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Mon, 13 Feb 2017 03:05:35 +0000 Subject: [PATCH] Fix malformed content-type header causing exception on charset get (#898) --- lib/request.js | 10 ++++++++-- test/request/charset.js | 6 ++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/request.js b/lib/request.js index 21a5a9d..a1be181 100644 --- a/lib/request.js +++ b/lib/request.js @@ -315,10 +315,16 @@ module.exports = { */ get charset() { - const type = this.get('Content-Type'); + let type = this.get('Content-Type'); if (!type) return ''; - return contentType.parse(type).parameters.charset || ''; + try { + type = contentType.parse(type); + } catch (e) { + return ''; + } + + return type.parameters.charset || ''; }, /** diff --git a/test/request/charset.js b/test/request/charset.js index ee6f260..2d44abb 100644 --- a/test/request/charset.js +++ b/test/request/charset.js @@ -26,5 +26,11 @@ describe('req.charset', () => { req.header['content-type'] = 'text/plain; charset=utf-8'; req.charset.should.equal('utf-8'); }); + + it('should return "" if content-type is invalid', () => { + const req = request(); + req.header['content-type'] = 'application/json; application/text; charset=utf-8'; + req.charset.should.equal(''); + }); }); });