【node 中间件】body-parser 中间件分析

README

Node.js 请求体中间件。将客户端请求的内容,解析并存储到req.body上。html

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

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

先对 bodyParser.json 作简要分析:github

bodyParser.json([options])

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

Options

inflate

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

limit

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

reviver

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

strict

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

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))
})

结构

图片描述

参考

相关文章
相关标签/搜索