I was wondering how can I submit a HTML form to my NodeJS server and get the information submitted without the use of express, body-parser or any other modules or npm?
I tried to look it up here on stackoverflow and searching on the internet, but i didn't find any one teching how to submit data from html form to vanilla NodeJS ( using the node API's )
I've came around many people that uses expressJS to do that task. and I understand why, but I want to deep dive and understand the core NodeJS API's better.
but unfortunately NodeJS API's documentations aren't that great it's very confusing and hard to navigate around and some functions aren't explained what arguments they take and how they work.
I've written the following code and I not sure how to go from there:
SERVER.JS
const fs = require('fs');
const http = require('http');
const PORT = 3000;
let server = http.createServer((req,res) =>{
if (req.url == '/'){
fs.readFile('./views/index.html', 'utf-8',(err,data) => {
if (err) {
console.log(err);
res.end();
}
res.write(data);
res.end();
});
}else{
res.writeHead(404,'Page not found');
res.end();
}
}).listen(PORT)
console.log(`Server is running on port ${PORT}, vist http://localhost:${PORT}`);
index.html
<!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>
<h1>Is your username taken?</h1>
<form method="POST" action="/">
<input type="text" name="USER">
<input type="submit" value='Check'>
</form>
</body>
</html>
File structure:
views
|
|_ index.html
server.js
The req object will have a method property that will tell you if it is a POST request.
If it is then, since it is a readable stream you can listen for data and end events on it to read the data in the body. (This is a fairly standard approach for Node.js where you can append to a string variable on each data event and then do something with the finished string on the end event so long as your incoming data isn't too large. A robust system would need to special case large requests to avoid trivial denial of service attacks that make the server run out of memory).
Then you'll need to parse it. Since you don't have an enctype attribute, it will be in the application/x-www-form-urlencoded format which is described in MDN's description of a POST request.