node-中间件bodyparser-中间件分析

34次阅读

共计 1440 个字符,预计需要花费 4 分钟才能阅读完成。

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-urlencoded
app.use(bodyParser.urlencoded({ extended: false}))

// parse application/json
app.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…

正文完
 0