nodejs库express是如何接收inbound json请求的
2023-09-14 09:03:58 时间
这样几行简单的代码创建一个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:
![](https://user-images.githubusercontent.com/5669954/64004132-448dcd00-cb40-11e9-8af7-b4cc48178a78.png)
调用layer的handle_request方法,这个很像SAP ABAP里的IF_HTTP_EXTENSION的HANDLE_REQUEST方法。
![](https://user-images.githubusercontent.com/5669954/64004133-448dcd00-cb40-11e9-8b1e-a3bdef18c071.png)
express中的中间件,query.js:
![](https://user-images.githubusercontent.com/5669954/64004134-45266380-cb40-11e9-9968-050c3029771d.png)
这个中间件里也用了直接和undefined做比较的方式:
![](https://user-images.githubusercontent.com/5669954/64004135-45266380-cb40-11e9-9a9f-da69867a37b6.png)
这里准备开始读取inbound json了:
![](https://user-images.githubusercontent.com/5669954/64004136-45266380-cb40-11e9-9a4f-3c1a4430a16b.png)
![](https://user-images.githubusercontent.com/5669954/64004139-45befa00-cb40-11e9-9798-65d5d62d338f.png)
通过stream上注册的回调函数onData进行数据读取:
读取了65018个字节的数据:
![](https://user-images.githubusercontent.com/5669954/64004140-45befa00-cb40-11e9-869d-c75f7960d833.png)
把读取的数据写到buffer里:
![](https://user-images.githubusercontent.com/5669954/64004141-46579080-cb40-11e9-8ce8-4fc6d3be02ed.png)
写的同时还被第252行的decoder进行了解码:
![](https://user-images.githubusercontent.com/5669954/64004142-46579080-cb40-11e9-88d0-a5b2dd31a0a0.png)
当inbound message的数据全部读取完毕后,触发End事件,执行注册的回调done函数:
![](https://user-images.githubusercontent.com/5669954/64004144-46579080-cb40-11e9-95af-f07300124e0b.png)
此时所有读取的数据都存放在变量body里了:
![](https://user-images.githubusercontent.com/5669954/64004127-43f53680-cb40-11e9-88c9-d6ca82c4ebeb.png)
这个json.js负责把body变量里包含的字符串解析成json对象:
![](https://user-images.githubusercontent.com/5669954/64004129-43f53680-cb40-11e9-919c-616143ff21f1.png)
由此可见,body-parser这个库最终使用的仍然是原生的JSON.parse API来完成解析任务。
![](https://user-images.githubusercontent.com/5669954/64004131-448dcd00-cb40-11e9-8ad7-4295db843959.png)
要获取更多Jerry的原创文章,请关注公众号"汪子熙":
相关文章
- [AaronYang]那天有个小孩跟我说Js-NodeJS[AY0]-EJS
- nodeJS 调试debug
- 单步调试理解webpack里通过require加载nodejs原生模块实现原理
- MongoDB最简单的入门教程之二 使用nodejs访问MongoDB
- Atitit 常见编程语言读写数据库的api目录1.1. Php pdo 11.2. Java jdbctmpltr 11.3. Nodejs mysql模块 11.4. Pytho
- Atitit nodejs5 nodejs6 nodejs 7.2.1 新特性attialx总结
- nodejs项目npm start背后的工作原理
- 给nodejs应用的package.json添加Redis服务的依赖
- nodejs对字符串进行base64转换和解析
- Nodejs环境搭建
- Nodejs入门一