1. 程式人生 > 實用技巧 >body-parser的使用

body-parser的使用

這幾天開啟以前寫的node服務程式碼,發現裡面有兩句

app.use(bodyParser.json({limit: '50mb'}));  //新增json解析
app.use(bodyParser.urlencoded({limit: '10mb',  extended: true }));

當時使用express生成的express專案,就直接使用了,沒注意,這次開啟,覺得這裡不是太懂,就往清楚搞一下。

其實bodyparser是express框架預設使用的中介軟體之一,常用來解析http請求體。

在使用express生成一個網站時,預設已經使用了bodyParser.json與bodyParser.urlencoded的解析功能,除了這兩個,bodyParser還支援對text、raw的解析,如下所示:

app.use(bodyParser.json());  //新增json解析
app.use(bodyParser.urlencoded({extended: true }));

bodyParser.json是用來解析json資料格式的。bodyParser.urlencoded則用來解析我們通常的form表單提交的資料,也就是請求頭中包含這樣的資訊:

Content-Type: application/x-www-form-urlencoded

常見的四種Content-Type型別: