Node中的核心子產品分兩類:一類是自帶的核心子產品,如http、tcp等,第二類是第三方核心子產品,express就是與http對應的第三方核心子產品,用于處理http請求。express在3.0版本中自帶有很多中間件,但是在express 4.0以後,就将除static(靜态檔案處理)以外的其他中間件分離出來了;在4.0以後需要使用中間件時,就需要單獨安裝好相應的中間件以後調用,以下3.0與4.0中間件的中間件差別(3.0是内置中間件屬性名,4.0是需要安裝的中間件名稱):
Express 3.0 Name | Express 4.0 Name |
bodyParser | body-parser |
compress | compression |
cookieSession | cookie-session |
logger | morgan |
cookieParser | cookie-parser |
session | express-session |
favicon | static-favicon |
response-time | response-time |
error-handler | errorhandler |
method-override | method-override |
timeout | connect-timeout |
vhost | vhost |
csrf | csurf |
*********************body-parser****************************
我是在學習nodejs時候,對着書本的例子時,使用bodyParser這個中間件,在終端運作出問題,報錯大概意思也是express4.0中沒有bodyParser這個内置中間件了,還給了body-parser的GitHub源代碼位址:https://github.com/expressjs/body-parser.
經過看源代碼下面的說明知道了body-parser的三種用法:
在講用法之間,我們需要弄清楚下面四個不同的處理方法:這四個處理方法分别對body的内容采用不同的處理方法;分别是處理json資料、Buffer流資料、文本資料、UTF-8的編碼的資料。
bodyParser.json(options)、bodyParser.raw(options)、bodyParser.text(options)、bodyParser.urlencoded(options)
以下是它的三種用法:
1、底層中間件用法:這将攔截和解析所有的請求;也即這種用法是全局的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
express的use方法調用body-parser執行個體;且use方法沒有設定路由路徑;這樣的body-parser執行個體就會對該app所有的請求進行攔截和解析。
2、特定路由下的中間件用法:這種用法是針對特定路由下的特定請求的,隻有請求該路由時,中間件才會攔截和解析該請求;也即這種用法是局部的;也是最常用的一個方式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
express的post(或者get)方法調用body-parser執行個體;且該方法有設定路由路徑;這樣的body-parser執行個體就會對該post(或者get)的請求進行攔截和解析。
3、設定Content-Type 屬性;用于修改和設定中間件解析的body類容類型。
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' });
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));
轉載:https://www.cnblogs.com/yangyabo/p/5401812.html