Hey there! I'm having an issue with the redirect not working when I click the "Submit" button on the login page.
The code in my index.js file looks like this:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public'), { "extensions": ["html", "css", "js"] }));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public/login.html'));
});
app.post('/login', (req, res) => {
console.log(req.body.username);
res.redirect('/chat');
});
app.get('/chat', (req, res) => {
res.sendFile(path.join(__dirname, 'public/chat.html'));
});
Here's a snippet from my login.html file:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/login.css">
<title>Log in</title>
</head>
<body>
<div class="wrapper">
<form action="/login" method="post" class="form">
<h1>Enter to the chat</h1>
<div class="username-container">
<label for="username">Your name:</label>
<input type="text" name="username" id="username" maxlength="10" required>
</div>
<button type="submit" id="submit">Submit</button>
</form>
</div>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="./js/login.js"></script>
</body>
Based on the project structure below:
./public
./css
./login.css
./styles.css
./js
./login.js
./main.js
./chat.html
./login.html
./index.js
I've also added some code from login.js regarding form submission:
form.addEventListener('submit', event => {
event.preventDefault();
console.log('Form submitted');
socket.emit('login', {
username: username.value.trim()
});
});
I see the message "Form submitted" in the console, but the redirect is not happening. Interestingly, it was working fine before I connected styles to the server and encountered MIME TYPE errors. There are no errors showing up in the console currently.