Hello there i see that you are trying to transfer form data from the frontend to the backend using an http request. Let's do that in an easier and more efficient way: You shall use packetgun-frontend and packetgun-backend npm packages like so (I made those. Don't read their docs it's bad):
In the frontend project folder run the following command
npm install packetgun-frontend
Then write the following in your code (replace ip with the ip of your server as well as port with the port you're listening with)
Html
<!DOCTYPE html>
<html>
<head>
<title>Cool form chat website</title>
</head>
<body>
<div id="form">
<h1 id="title">Enter a message:</h1>
<input type="text" id="message" placeholder="Hello i am a cool dev">
<button id="send">Send</button>
</div>
</body>
</html>
<!--The path may be a bit different sometimes-->
<script src="node_modules/packetgun-frontend/packetgun-frontend.js"></script>
<script src="./app.js"></script>
Javascript [app.js]
//Get textbox
var message = document.getElementById("message");
//Get button
var send = document.getElementById("send");
var open = function(){
packetgun.recommended("127.0.0.1:1234", function (client) {
send.onclick = function () {
//On button click send form data...
client.send({
"exit_code": 0,
"data": JSON.stringify({
"message": message.value
})
})
//Empty textbox
message.value = "";
}
message.onkeydown = function (event) {
//If pressed enter key while in the textbox
if (event.keyCode === 13) {
//Click the button
send.click();
}
}
client.on("serverDisconnect", function(){
//On client close restart the process
open();
})
})
}
open()
In your node.js project folder run the following command
npm install packetgun-backend
Then write the following in your code (replace port with the port you want to use):
//Require packetgun
var packetgun = require("packetgun-backend");
//Init packetgun
packetgun.init()
//Listen with recommended method
packetgun.listen.recommended(port, function(client){
//When receiving data from client
client.on("data", function(data){
//Ignore exit_code and client_exit_code just get client data
data = data.data;
//Check if data requires preprocessing
if (typeof data === "string"){
try{
//Preprocess data
data = JSON.parse(data)
}
catch (error){
//Client data is corrupted
console.error("Client data is corrupted :(");
client.close();
}
}
//Close client to mimic an http request (disconnect client)
client.close();
//data is the JSON object you sent from the frontend side containing the form data, use that data as you whish
//For exemple let's stringify and log the data
console.log(JSON.stringify(data, null, 4));
})
})
I tested this code, and it works!
FormData.