在 Nodejs 中,http 服务器 req.on('data') 没有触发



我正在学习Nodejs。我正在尝试了解读取流在Node.js中的HTTP服务器中是如何工作的。这是我的密码。这是req.on('data'(事件未启动。如果可以的话,请帮帮我。非常感谢。

代码-

const http = require('http');
const server = http.createServer(onConnect);
server.listen(3000);
const homePage = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="/process" method="post">
<h3>Enter your text here</h3>
<br />
<input type="text" />
</form>
</body>
</html>

`;
function onConnect(req, res) {
if (req.url === '/') {
res.write(homePage);
} else if (req.url === '/process' && req.method === 'POST') {
req.on('data', (chunck) => {
console.log(chunck);
});
res.write('<h1>Thank you for your submission</h1>');
} else {
res.write('No page found');
}
res.end();
}
正如@robertklep正确指出的,您需要在输入元素上定义name属性。

但是,您还需要在请求对象上定义'end'事件,以便代码正常工作。典型的设置如下:

function onConnect(req, res) {
if (req.url === '/') {
res.write(homePage);
} else if (req.url === '/process' && req.method === 'POST') {
let requestBody = "";
req.on('data', (chunck) => {
requestBody += chunck;
});
req.on('end', () => {
console.log(requestBody);
});
res.write('<h1>Thank you for your submission</h1>');
} else {
res.write('No page found');
}
res.end();
}

如果您不提供;name";属性,您的浏览器将不会发布它。

所以试试这个:

<input type="text" name="mytext" />

最新更新