安裝
$ npm install body-parser
API
var bodyPaeser =require('body-parser')
可以通過body-parser 對象創(chuàng)建中間件,當(dāng)接收到客戶端請求時(shí)所有的中間件都會(huì)給req.body 添加屬性,請求體為空,則解析為空{(diào)} (或者出現(xiàn)錯(cuò)誤)。
bodyParser.json(options)
中間件只會(huì)解析 json ,允許請求提任意Unicode編碼支持 gzip 和 deflate 編碼。
options
一個(gè)對象,有以下屬性
inflate
默認(rèn)為false,true->壓縮的請求體會(huì)被解壓,false->壓縮的請求提不被解壓。
limit
控制請求體最大大小,默認(rèn)為100kb,當(dāng)為數(shù)字時(shí)會(huì)轉(zhuǎn)換為bytes,當(dāng)為字符串時(shí),value值會(huì)通過 bytes庫 轉(zhuǎn)換為字節(jié)大小。
reviver
此選項(xiàng)會(huì)通過JSON.parse直接傳給其第二個(gè)參數(shù)。
strict
默認(rèn)為true,當(dāng)為true時(shí)只接受數(shù)組和對象,當(dāng)為false時(shí)會(huì)接受任何JSON.parse 能接受的。
type
type 選項(xiàng)用來決定中間件要解析媒體類型。選項(xiàng)可以是一個(gè)函數(shù)或者是字符串。當(dāng)為字符串時(shí),可以直接通過type-is 庫直接傳遞給選項(xiàng),字符串也可以為一個(gè)擴(kuò)展名(例如json)、mime 類型(application/json、/ 、*/json)。當(dāng)為函數(shù)時(shí):默認(rèn)為application/json。
verify
verify選項(xiàng),若缺失則為一個(gè)函數(shù)function(req,res,buf,encoding),buf為一個(gè)Buffer。
bodyParse.raw(option)
將請求體內(nèi)容作為Buffer來處理,并返回。支持gzip deflate 壓縮。
inflate
limit
type
verify
bodyParser.text(option)
將請求提內(nèi)容作為字符串來處理,并返回。支持gzip deflate 壓縮。
defaultCharset
若請求頭未設(shè)置Content-Type則默認(rèn)為utf8
inflate
type
verify
bodyParser.urlencoded(option)
中間件只解析urlencoded 請求體,并返回,只支持UTF-8編號文本,支持gzip deflate 壓縮。
extend
ture->使用queryString庫(默認(rèn)) false->使用qs庫。
limit
parameterlimit
指定parameters最長長度,默認(rèn)1000
type
verify
舉例:
const express=require('express'); const bodyParser=require('body-parser'); var server=express(); server.listen(8080); server.use(bodyParser.urlencoded({ extended: false, //擴(kuò)展模式 limit: 2*1024*1024 //限制-2M })); server.use('/', function (req, res){ console.log(req.body); //POST //req.query GET //req.body POST });
html代碼:
<form action="http://localhost:8080" method="post"> 用戶:<input type="text" name="user" /><br> 密碼:<input type="password" name="pass" /><br> <input type="submit" value="提交" >
以上這篇nodejs body-parser 解析post數(shù)據(jù)實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com