nodejs庫express是如何接收inbound json請求的

i042416發表於2019-09-28

這樣幾行簡單的程式碼建立一個web伺服器:

var express = require('express');var app = express();var server = require('http').Server(app);var bodyParser = require('body-parser');app.use(bodyParser.json({limit: '10mb', extended: true}));

然後使用app.post("/getSimilarImage", function(req, res){
// 此處編寫業務邏輯
});

就可以接收json請求了。問題就是,我通過postman傳送的json字串,是如何被nodejs的express庫處理的呢?

除錯一下,trim_prefix的引數path即我在postman裡測試的API endpoint:

nodejs庫express是如何接收inbound json請求的

呼叫layer的handle_request方法,這個很像SAP ABAP裡的IF_HTTP_EXTENSION的HANDLE_REQUEST方法。

nodejs庫express是如何接收inbound json請求的

express中的中介軟體,query.js:

nodejs庫express是如何接收inbound json請求的

這個中介軟體裡也用了直接和undefined做比較的方式:

nodejs庫express是如何接收inbound json請求的

這裡準備開始讀取inbound json了:

nodejs庫express是如何接收inbound json請求的


nodejs庫express是如何接收inbound json請求的

通過stream上註冊的回撥函式onData進行資料讀取:
讀取了65018個位元組的資料:

nodejs庫express是如何接收inbound json請求的

把讀取的資料寫到buffer裡:

nodejs庫express是如何接收inbound json請求的

寫的同時還被第252行的decoder進行了解碼:

nodejs庫express是如何接收inbound json請求的

當inbound message的資料全部讀取完畢後,觸發End事件,執行註冊的回撥done函式:

nodejs庫express是如何接收inbound json請求的

此時所有讀取的資料都存放在變數body裡了:

nodejs庫express是如何接收inbound json請求的

這個json.js負責把body變數裡包含的字串解析成json物件:

nodejs庫express是如何接收inbound json請求的

由此可見,body-parser這個庫最終使用的仍然是原生的JSON.parse API來完成解析任務。

nodejs庫express是如何接收inbound json請求的

要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":


nodejs庫express是如何接收inbound json請求的


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24475491/viewspace-2658615/,如需轉載,請註明出處,否則將追究法律責任。

相關文章