I need to transfer the data from the form to the server (created on the nodeJS express framework), for further use of the data from the forms. But the "send" button should send the user to another html page (I create a chat, the first html is registration, the second is the chat itself, with registration data). What should I specify in the action method in order to transfer data to the index.js server, but at the same time open an html page that is located on a different path.
index.html (registration):
<form action="/index" method="post" >
<label>Username</label><br>
<input type="TEXT" autocomplete="off" name="Username"/>
<button type="submit" onclick="redirect()" >Send</button>
</form>
redirect() - initially, when there was no need to send to the server, redirected to the page with the chat (using window.location).
index.js
const express = require('express');
const app = express();
const db = require('./database/database');
const bodyParser = require('body-parser');
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 = {};
const urlencodedParser = bodyParser.urlencoded({
extended: false,
})
app.use(express.static(__dirname));
app.get('/index', (request, response ) => {
response.sendFile(__dirname '/index.html');
});
app.post('/index', urlencodedParser, function (
request,
response
) {
if (!request.body) return response.sendStatus(400)
console.log(request.body.Username)
})
io.on('connection', (socket) => {
.....
CodePudding user response:
The action should be the URL you want to send the form data to.
The end point in your Express code which matches that URL should be responsible for processing the submitting data and sending the response back to the browser.
Typically that response will be the HTML document you want to send back. You might want to issue a redirect response to tell the browser to make a second request to a different URL.
