request的请求体数据获取

表单

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <title>form表单</title>
 7 </head>
 8 <body>
 9     <!-- action 设置的是表单提交的 URL, -->
10     <form action="http://localhost:8000" method="POST">
11         用户名: <input type="text" name="username"><br>
12         密码: <input type="password" name="password"><br>
13         <button>点击登录</button>
14     </form>
15 </body>
16 </html>

http服务

 1 // querystring 模块提供用于解析和格式化 URL 查询字符串的实用工具。 可以使用以下方式访问它:
 2 // querystring.parse() 方法将 URL 查询字符串 str 解析为键值对的集合。
 3 
 4 
 5 //1. 
 6 const http = require('http');
 7 const querystring = require('querystring');
 8 const qs = require("querystring");
 9 
10 //2. 
11 const server = http.createServer((request, response)=>{
12     //提取表单中的用户名和密码
13     //1. 声明一个变量
14     let body = '';
15     //2. 绑定 data 事件
16     request.on('data', (chunk) => {
17         //每次读取是64kb,需要多次读取
18         body += chunk;   //chunk是二进制数据,和字符串相加也是字符串
19     });
20     //3. 绑定 end 事件
21     request.on('end', ()=>{
22         // console.log(body);
23         // 将字符串转化为对象
24         const data = qs.parse(body);
25         console.log(data);
26         response.end("over");
27     });
28 
29 });
30 
31 //3. 
32 server.listen(8000, ()=>{
33     console.log('服务已经启动, 8000 端口监听中.....');
34 })
原文地址:https://www.cnblogs.com/fsg6/p/13081878.html