-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.js
More file actions
61 lines (53 loc) · 1.26 KB
/
json.js
File metadata and controls
61 lines (53 loc) · 1.26 KB
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
/*!
* Connect - json
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('../utils');
/**
* JSON:
*
* Parse JSON request bodies, providing the
* parsed object as `req.body`.
*
* Options:
*
* - `strict` when `false` anything `JSON.parse()` accepts will be parsed
* - `reviver` used as the second "reviver" argument for JSON.parse
*
* @param {Object} options
* @return {Function}
* @api public
*/
exports = module.exports = function(options){
var options = options || {}
, strict = options.strict === false
? false
: true;
return function json(req, res, next) {
if (req._body) return next();
req.body = req.body || {};
// check Content-Type
if ('application/json' != utils.mime(req)) return next();
// flag as parsed
req._body = true;
// parse
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
if (strict && '{' != buf[0] && '[' != buf[0]) return next(utils.error(400));
try {
req.body = JSON.parse(buf, options.reviver);
next();
} catch (err){
err.status = 400;
next(err);
}
});
}
};