Skip to content

Commit 9db582d

Browse files
committed
Fix error message for json parse whitespace in strict
1 parent bd702d2 commit 9db582d

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

HISTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
unreleased
22
==========
33

4+
* Fix error message for json parse whitespace in `strict`
45
* Prevent loss of async hooks context
56
* Prevent hanging when request already read
67

lib/types/json.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ module.exports = json
3737
* %x0D ) ; Carriage return
3838
*/
3939

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

4242
/**
4343
* Create a middleware to parse JSON bodies.
@@ -152,7 +152,9 @@ function json (options) {
152152

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

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

175177
function firstchar (str) {
176-
return FIRST_CHAR_REGEXP.exec(str)[1]
178+
var match = FIRST_CHAR_REGEXP.exec(str)
179+
180+
return match
181+
? match[1]
182+
: undefined
177183
}
178184

179185
/**

test/json.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ describe('bodyParser.json()', function () {
4444
.expect(200, '{}', done)
4545
})
4646

47+
it('should 400 when only whitespace', function (done) {
48+
request(createServer())
49+
.post('/')
50+
.set('Content-Type', 'application/json')
51+
.send(' \n')
52+
.expect(400, '[entity.parse.failed] ' + parseError(' '), done)
53+
})
54+
4755
it('should 400 when invalid content-length', function (done) {
4856
var jsonParser = bodyParser.json()
4957
var server = createServer(function (req, res, next) {

0 commit comments

Comments
 (0)