I am implementing a chat, creating a registration window, and it is necessary that the data from the form be sent to the server, so that it is then sent to the client side to be displayed in the list of clients. But for some reason the data from the form does not come, what's the problem? Here is the form index.html:
<form class = "FORM" action="/" method="post">
<label>Username</label><br>
<input type = "TEXT" class = "CHECK" autocomplete="off" name="Username">
<button type = "submit" class="BTN" onclick="redirect()">Send</button>
</form>
Here is the server on express index.js
const express = require('express');
const app = express();
const db = require('./database/database'); // подключаемся к бд
const urlencodedParser = express.urlencoded({extended: false});
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);
const port = 3000;
let id = 0;
let users = {};
app.use(express.static(__dirname));
app.get('/', (request, response ) => {
response.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
app.post("/", urlencodedParser, function (request, response) {
if(!request.body) return response.sendStatus(400);
console.log(request.body);
//response.send(`${request.body.userName} - ${request.body.userAge}`);
});
.....
Why is the data not coming from the form to the server?
You would have to make an axios post request to the endpoint.
if you're using vanilla javascript, you also need to add eventlistener to the form.
const form = document.getElementsByClassName("FORM");
form.addEventListener("submit", (event) => {
event.preventDefault();
const userName = event.target.Username.value;
if (!userName) alert("Username is required");
else {
axios
.post(
"http://localhost:3000/", {
userName
})
.then((response) => {
console.log(response.data);
/*depending on what response you get from the server,
you may want to use .map() method to display all the usernames*/
})
.catch((error) => console.log(error));
event.target.reset();
}
})