json.js 3.5 KB

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