I understand I could do that with <form action=/serverfile.js method='post'>
, but:
(1) How does one do it with Ajax/Fetch API since they need you to send through a file, like a txt file? I'm only trying to send a string.
(2) How would one do it with <form action=/serverfile.js method='post'>
too, what would need to be set up on the server end to collect the incoming data?
The answers I have seen use expressjs. I don't want to use expressjs. Is it impossible to do this with vanilla NodeJS?
One way I found to do this with vanilla NodeJS is like so:
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);
When I do this though, the inputed text doesn't get posted, only "You Posted:". And how would one do that with an HTML page with multiple post requests, if the way to intercept incoming data is request.method === "POST"
?
Edit: Used querystring. Still doesn't work.
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 either:
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);