1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
/*!
* body-parser
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module dependencies.
*/
var bytes = require('bytes')
var read = require('../read')
var typer = require('media-typer')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = json
/**
* RegExp to match the first non-space in a string.
*
* Allowed whitespace is defined in RFC 7159:
*
* ws = *(
* %x20 / ; Space
* %x09 / ; Horizontal tab
* %x0A / ; Line feed or New line
* %x0D ) ; Carriage return
*/
var firstcharRegExp = /^[\x20\x09\x0a\x0d]*(.)/
/**
* Create a middleware to parse JSON bodies.
*
* @param {object} [options]
* @return {function}
* @api public
*/
function json(options) {
options = options || {}
var limit = typeof options.limit !== 'number'
? bytes(options.limit || '100kb')
: options.limit
var inflate = options.inflate !== false
var reviver = options.reviver
var strict = options.strict !== false
var type = options.type || 'json'
var verify = options.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
function parse(body) {
if (body.length === 0) {
// special-case empty json body, as it's a common client-side mistake
// TODO: maybe make this configurable or part of "strict" option
return {}
}
if (strict) {
var first = firstchar(body)
if (first !== '{' && first !== '[') {
throw new Error('invalid json')
}
}
return JSON.parse(body, reviver)
}
return function jsonParser(req, res, next) {
if (req._body) return next()
req.body = req.body || {}
if (!typeis(req, type)) return next()
// RFC 7159 sec 8.1
var charset = (typer.parse(req).parameters.charset || 'utf-8').toLowerCase()
if (charset.substr(0, 4) !== 'utf-') {
var err = new Error('unsupported charset "' + charset.toUpperCase() + '"')
err.charset = charset
err.status = 415
next(err)
return
}
// read
read(req, res, next, parse, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Get the first non-whitespace character in a string.
*
* @param {string} str
* @return {function}
* @api public
*/
function firstchar(str) {
var match = firstcharRegExp.exec(str)
return match ? match[1] : ''
}
|