Skip to content

Commit

Permalink
Fix error message for json parse whitespace in strict
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Mar 23, 2022
1 parent bd702d2 commit 9db582d
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
@@ -1,6 +1,7 @@
unreleased
==========

* Fix error message for json parse whitespace in `strict`
* Prevent loss of async hooks context
* Prevent hanging when request already read
* deps: depd@2.0.0
Expand Down
12 changes: 9 additions & 3 deletions lib/types/json.js
Expand Up @@ -37,7 +37,7 @@ module.exports = json
* %x0D ) ; Carriage return
*/

var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex
var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex

/**
* Create a middleware to parse JSON bodies.
Expand Down Expand Up @@ -152,7 +152,9 @@ function json (options) {

function createStrictSyntaxError (str, char) {
var index = str.indexOf(char)
var partial = str.substring(0, index) + '#'
var partial = index !== -1
? str.substring(0, index) + '#'
: ''

try {
JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
Expand All @@ -173,7 +175,11 @@ function createStrictSyntaxError (str, char) {
*/

function firstchar (str) {
return FIRST_CHAR_REGEXP.exec(str)[1]
var match = FIRST_CHAR_REGEXP.exec(str)

return match
? match[1]
: undefined
}

/**
Expand Down
8 changes: 8 additions & 0 deletions test/json.js
Expand Up @@ -44,6 +44,14 @@ describe('bodyParser.json()', function () {
.expect(200, '{}', done)
})

it('should 400 when only whitespace', function (done) {
request(createServer())
.post('/')
.set('Content-Type', 'application/json')
.send(' \n')
.expect(400, '[entity.parse.failed] ' + parseError(' '), done)
})

it('should 400 when invalid content-length', function (done) {
var jsonParser = bodyParser.json()
var server = createServer(function (req, res, next) {
Expand Down

0 comments on commit 9db582d

Please sign in to comment.