如何将来自 <input> HTML 标记的值的字符串发送到 NodeJS 服务器?

How does one send a string which is a value from an <input> HTML tag to a NodeJS server?

我知道我可以用 <form action=/serverfile.js method='post'> 做到这一点,但是:

(1) 如何使用 Ajax/Fetch API,因为他们需要您发送一个文件,例如 txt 文件?我只是想发送一个字符串。

(2) 如何用 <form action=/serverfile.js method='post'> 做到这一点,需要在服务器端设置什么来收集传入数据?

我看到的答案都是用expressjs的。我不想使用 expressjs。用 vanilla NodeJS 不可能做到这一点吗?

我发现使用 vanilla NodeJS 执行此操作的一种方法如下:

HTML

<form action="/nodedemo_trial" method="post">
<label> Username </label> <br/> <br/>
<input type="text" style="width:200px; font-size:1.5rem" id="username"> <br/> <br/>
<label> Password </label> <br/> <br/>
<input type="text" style="width:200px; font-size:1.5rem" id="password"> <br/> <br/>
<input type="submit" value="Log In" style="width:120px; font-size:1.5rem;" > <br/> <br/>
<input type="submit" value="Sign Up" style="width:120px; font-size:1.5rem;" > <br/> <br/>
</form>

NodeJS:

var http = require('http');
var form = require('fs').readFileSync('homepage.html');
http.createServer(function (request, response) {
if (request.method === "GET") {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(form);
}


if (request.method === "POST") {
var postData = '';
request.on('data', function (chunk) {
postData += chunk;
}).on('end', function() {
console.log('User Posted:\n' + postData);
response.end('You Posted:\n' + postData);
});
}

}).listen(1000);

不过,当我执行此操作时,输入的文本不会得到 posted,只有“您发布:”。如果拦截传入数据的方式是 request.method === "POST"?

,那么如何使用具有多个 post 请求的 HTML 页面做到这一点

编辑:使用查询字符串。还是不行。

var http = require('http');
var qs = require('querystring');

var form = require('fs').readFileSync('homepage.html');

http.createServer(function (request, response) {
    
if (request.method === "GET") {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(form);
}


if (request.method === "POST") {
var postData = '';
request.on('data', function (chunk) {
postData += chunk;
}).on('end', function() {
var post = qs.stringify(postData);
console.log('User Posted:\n' + post);
response.end('You Posted:\n' + post);
});
}

}).listen(1000);

也不是异步的:

var http = require('http');
var fs = require('fs');
var qs = require('querystring');


http.createServer(function (req, res) {

  fs.readFile('homepage.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);


if (req.method == 'POST') {

        var body = '';

        req.on('data', function (data) {
            body += data;
            if (body.length > 1e6)
                req.connection.destroy();
        }).on('end', function () {
            var post = qs.stringify(body);
            console.log(post);
           //res.end(post);
        });
    } 
    return res.end();
  });
}).listen(8082);

最佳答案 here 有效。

显然,您需要使用querystring.parse(postData) 截取数据以将其转换为对象。通过 querystring.stringify(postData) 或 String(postData)/postData.toString 将其转换为字符串是行不通的。没有 为什么不呢。