README

Node.js 请求体中间件。将客户端请求的内容,解析并存储到req.body上。
TODO: req.body 在解析之前是否有值?

Learn about the anatomy of an HTTP transaction in Node.js.

body-parser 不处理附件上传的解析(multipart bodies). 想要学习附件上传的中间件,需要查看:

  • multiparty
  • connect-multiparty

先对 bodyParser.json 做简要分析:

bodyParser.json([options])

调用此函数,返回处理 Content-Type:application/json的中间件。

Options

inflate

当被设置为true时,被压缩的请求体将被解压缩。如果设置为false,被压缩的请求体将被拒绝,并返回415数据格式解析错误。

limit

控制请求体最大大小,默认为100kb。当为数字时会转换为bytes,当为字符串时,value值会通过 bytes转换为字节大小。

reviver

此选项会通过JSON.parse直接传给其第二个参数。MDN JSON.parse

strict

默认为true,当为true时只接受数组和对象,当为false时会接受任何JSON.parse 能接受的。

type

该参数用于设置为指定MIME类型的数据使用当前解析中间件。该参数可以是一个函数或是字符串,当是字符串是会使用type-is来查找MIMI类型;当为函数是,中间件会通过fn(req)来获取实际值。默认为application/json

如,

// 对text/plain内容类型使用JSON解析:app.use(bodyParser.json({ type: 'text/plain' }))// 将 HTML 请求体做为字符串处理app.use(bodyParser.text({ type: 'text/html' }))
verify

verify参数本身是用于对请求的校验。当校验失败的时候通过抛出error来中止body-parser的解析动作,在这里被借用来实现post参数raw body的获取。

app.use(bodyParser.json({    verify: function (req, res, buf, encoding) {        req.rawBody = buf;    }}));

Demo

var express = require('express')var bodyParser = require('body-parser')var app = express()// parse application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({ extended: false }))// parse application/jsonapp.use(bodyParser.json())app.use(function (req, res) {  res.setHeader('Content-Type', 'text/plain')  res.write('you posted:\n')  res.end(JSON.stringify(req.body, null, 2))})

参考

  • node官网 - zlib
  • github - body-parser
  • githistory - body-parser/json.js
  • githistory - read.js
  • https://segmentfault.com/a/11...