Node.js学习笔记4:querystring模块解析post数据请求

上一篇内容讲到原生node.js如何用url模块处理get数据请求,这篇记录如何用querystring模块处理post数据请求。

当form表单采用post方法提交数据时,服务器接收数据的方式不同于get方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const http = require('http');
const querystring = require('querystring');

http.createServer(function(req, res) {
let str = '';
let n = 0;
req.on('data', function(data) {
//数据分段传输,每个data都是数据的一部分
//传递大量数据时,可以用n来显示传递的次数
str += data;
console.log(`第${++n}次接收数据`);
})
req.on('end', function() {
//数据的形式也是xxx=xxx&xxx=xxx,所以用querystring.parse方法解析
let POST = querystring.parse(str);
console.log(POST);
})
}).listen(8080);
console.log("server running");

输出结果

如果将输出结果部分的console.log(POST)注释掉,同时增加数据量,就很容易看到post数据时是分段传输的。

我将O Captain! My Captain!复制了几十遍试了一下

get和post请求处理模型