如何将一个字符串作为一个值从<input>HTML标签发送到NodeJS服务器?



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

(1)如何做它与Ajax/Fetch API,因为他们需要你通过一个文件,如txt文件发送?我只是想发送一个字符串。

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

我看到的答案使用expressjs。我不想使用expressjs。是不可能做到这一点与香草NodeJS?

我发现在普通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);

当我这样做时,输入的文本不会被发布,只有"You张贴:"。如果拦截传入数据的方式是request.method === "POST",那么如何使用具有多个post请求的HTML页面呢?

编辑:使用querystring。还是不行

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);

Not async:

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);

上面的答案可以。

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

最新更新