body-parser的使用


最近在學習項目的過程中接觸到了node.js。學習過程中,對express框架的一些語法和中間件不是很明白。比如說body-parser。為什么要使用它?它有什么作用?這篇就來對body-parser做一下筆記。

bodyParser中間件

bodyParser中間件用來解析http請求體,是express默認使用的中間件之一。那么首先就要引入bodyParser

 

 

 使用express生成一個網站,它默認已經使用了bodyParser.json與bodyParser.urlencoded的解析功能,除了這兩個,bodyParser還支持對text、raw的解析。

 

 

 那么顧名思義,bodyParser.json是用來解析json數據格式的。bodyParser.urlencoded則用來解析我們通常的form表單提交的數據,也就是請求頭中包含這樣的信息:

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

常見的四種Content-Type類型:

  • application/x-www-form-urlencoded 常見的form提交
  • multipart/form-data 文件提交
  • application/json  提交json格式的數據
  • text/xml  提交xml格式的數據

詳細解讀 urlencoded

bodyParser.urlencoded模塊用於解析req.body的數據,解析成功后覆蓋原來的req.body。如果解析失敗則為{}。該模塊有一個屬性extended,官方介紹如下:

The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true).

Defaults to true, but using the default has been deprecated.

大致的意思就是:extended選項允許配置使用querystring(false)或qs(true)來解析數據,默認值是true,但這已經是不被贊成的了。

querystring就是nodejs內建的對象之一,用來字符串化對象或解析字符串。如

querystring.parse("name=henry&age=30") => { name: 'henry', age: '30' }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM