在节点中解析请求主体
在简单的代码示例前面,我们看到了如何路由请求并创建文件以输入测试数据。
现在,我们要将用户输入的输入数据保存到文本文件中。
Node.js如何处理传入的请求数据
Node.js读取数据块是指它使用流读取数据。节点完成读取请求数据后,我们可以继续将其用于我们的目的。
First read data in chunks
const requestBody = [];
req.on(‘data’, (chunks)=>{
requestBody.push(chunks);
});我们已经在传入的HTTP请求中注册了一个名为“数据”的事件。此事件将继续流数据并推送到requestBodyconst变量。
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();
});我们以键值对的形式获取请求参数。我们必须将其拆分以将值保存在文本文件中。
constusername=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 nhooo </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);
});
//重定向
res.statusCode=302;
res.setHeader('Location','/');
return res.end();
}
res.write('<html>');
res.write('<head> <title> Hello nhooo </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处理请求解析的方法。