解析 Node 中的请求正文
在之前的简单代码示例中,我们了解了如何路由请求以及创建文件以输入测试数据。
现在,我们需要将用户输入的输入数据保存到文本文件中。
Node.js 如何处理传入的请求数据
Node.js 以片段的形式读取数据,这意味着它使用流来读取数据。一旦 Node 完成了读取请求数据的操作,我们就可以继续使用该数据来实现我们的目的。
First read data in chunks
const requestBody = [];
req.on(‘data’, (chunks)=>{
requestBody.push(chunks);
});我们注册了对传入 http 请求的“data”事件。此事件将继续传输流数据并将其推送到 requestBody 常量变量中。
Append the whole request data
Once data is completed, we will convert the received data to string with ‘end ’ event
req.on(‘end’, ()=>{
const parsedData = Buffer.concat(requestBody).toString();
});我们以键值对的形式获取请求参数。我们需要对它进行拆分才能将值保存在文本文件中。
const username = parsedData.split(‘=’)[1];
完整的 App.js 文件及保存用户输入名称的代码如下 −
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res)=>{
const url = req.url;
if(url === '/'){
res.write('<html>');
res.write('<head> <title> Hello TutorialsPoint </title> </head>');
res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/> <button type="submit">Submit</button> </body>');
res.write('</html>');
return res.end();
}
if(url === '/username' && req.method === 'POST'){
const requestBody = [];
req.on('data', (chunks)=>{
requestBody.push(chunks);
});
req.on('end', ()=>{
const parsedData = Buffer.concat(requestBody).toString();
const username = parsedData.split('=')[1];
fs.writeFileSync('username.txt', username);
});
//redirect
res.statusCode=302;
res.setHeader('Location','/');
return res.end();
}
res.write('<html>');
res.write('<head> <title> Hello TutorialsPoint </title> </head>');
res.write(' <body> Hello </body>');
res.write('</html>');
res.end();
});
server.listen(3000);
Note that we wrote file write operation inside end event :
req.on('end', ()=>{
const parsedData = Buffer.concat(requestBody).toString();
const username = parsedData.split('=')[1];
fs.writeFileSync('username.txt', username);
});这是因为我们希望首先完成结束事件以获取用户名,然后再将它写入文件。
现在,这是使用核心 node.js 进行工作的背景知识,这样可以更轻松地以更简单的方式在 Express.js 中处理所有这些解析逻辑。
我们在后续的文章中将介绍 express.js 处理请求解析的方式。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP