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

結構

圖片描述

參考

相關文章
相關標籤/搜索