nodejs body-parser 解析post數據實例

安裝html

1node

$ npm install body-parserexpress

APInpm

1json

var bodyPaeser =require('body-parser')數組

能夠經過body-parser 對象建立中間件,當接收到客戶端請求時全部的中間件都會給req.body 添加屬性,請求體爲空,則解析爲空{} (或者出現錯誤)。app

bodyParser.json(options)函數

中間件只會解析 json ,容許請求提任意Unicode編碼支持 gzip 和 deflate 編碼。post

optionsui

一個對象,有如下屬性

inflate

默認爲false,true->壓縮的請求體會被解壓,false->壓縮的請求提不被解壓。

limit

控制請求體最大大小,默認爲100kb,當爲數字時會轉換爲bytes,當爲字符串時,value值會經過 bytes庫 轉換爲字節大小。

reviver

此選項會經過JSON.parse直接傳給其第二個參數。

strict

默認爲true,當爲true時只接受數組和對象,當爲false時會接受任何JSON.parse 能接受的。

type

type 選項用來決定中間件要解析媒體類型。選項能夠是一個函數或者是字符串。當爲字符串時,能夠直接經過type-is 庫直接傳遞給選項,字符串也能夠爲一個擴展名(例如json)、mime 類型(application/json、/ 、*/json)。當爲函數時:默認爲application/json。

verify

verify選項,若缺失則爲一個函數function(req,res,buf,encoding),buf爲一個Buffer。

bodyParse.raw(option)

將請求體內容做爲Buffer來處理,並返回。支持gzip deflate 壓縮。

inflate

limit

type

verify

bodyParser.text(option)

將請求提內容做爲字符串來處理,並返回。支持gzip deflate 壓縮。

defaultCharset

若請求頭未設置Content-Type則默認爲utf8

inflate

type

verify

bodyParser.urlencoded(option)

中間件只解析urlencoded 請求體,並返回,只支持UTF-8編號文本,支持gzip deflate 壓縮。

extend

ture->使用queryString庫(默認) false->使用qs庫。

limit

parameterlimit

指定parameters最長長度,默認1000

type

verify

舉例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

const express=require('express');

const bodyParser=require('body-parser');

  

var server=express();

server.listen(8080);

  

server.use(bodyParser.urlencoded({

 extended: false,         //擴展模式

 limit:  2*1024*1024      //限制-2M

}));

  

server.use('/', function (req, res){

 console.log(req.body); //POST

 //req.query  GET

 //req.body  POST

});

html代碼:

1

2

3

4

<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數據實例

相關文章
相關標籤/搜索