Home  >  Q&A  >  body text

node.js - Express 框架的body-parser的用法

怪我咯怪我咯2761 days ago800

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 16:12:33

    Wait, I overturned

    It first performs formatting constraints according to the options you gave when using, and then converts it once according to json. If there is no error, then calls urlencoded to receive and format other content of the form.

    When converting json, the content-type is used to specify the format by default. Check whether the request header is json. If not, it defaults to an empty value. Otherwise, format json, and then follow the urlencoded logicvar type = opts.type || 'application/json'

    The source code is as follows

    https://github.com/expressjs/...

    function bodyParser (options) {
      var opts = {}
    
      // exclude type option
      if (options) {
        for (var prop in options) {
          if (prop !== 'type') {
            opts[prop] = options[prop]
          }
        }
      }
    
      var _urlencoded = exports.urlencoded(opts)
      var _json = exports.json(opts)
    
      return function bodyParser (req, res, next) {
        _json(req, res, function (err) {
          if (err) return next(err)
          _urlencoded(req, res, next)
        })
      }
    }

    reply
    0
  • Cancelreply