这样几行简单的代码创建一个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:

调用layer的handle_request方法,这个很像SAP ABAP里的IF_HTTP_EXTENSION的HANDLE_REQUEST方法。

express中的中间件,query.js:

这个中间件里也用了直接和undefined做比较的方式:

这里准备开始读取inbound json了:


通过stream上注册的回调函数onData进行数据读取:
读取了65018个字节的数据:

把读取的数据写到buffer里:

写的同时还被第252行的decoder进行了解码:

当inbound message的数据全部读取完毕后,触发End事件,执行注册的回调done函数:

此时所有读取的数据都存放在变量body里了:

这个json.js负责把body变量里包含的字符串解析成json对象:

由此可见,body-parser这个库最终使用的仍然是原生的JSON.parse API来完成解析任务。
