I need my user to be redirected upon success. What I have now does not redirect but will present the success pop up message at the end of the form.
JSX File
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Navigate } from 'react-router-dom';
const Login = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loginStatus, setLoginStatus] = useState('');
axios.defaults.withCredentials = true;
const login = (event) => {
event.preventDefault();
axios
.post('http://localhost:5000/login', {
username: username,
password: password,
})
.then((response) => {
if (response.data.message) {
setLoginStatus(response.data.message);
} else {
setLoginStatus(response.data.username);
return <Navigate to="/admin/home" />;
}
})
.catch((error) => {
console.error('Error logging in:', error);
});
};
useEffect(() => {
axios
.get('http://localhost:5000/check-session')
.then((response) => {
if (response.data.loggedIn) {
return <Navigate to="/admin/home" />;
// Redirect to /admin/home if already logged in
}
})
.catch((error) => {
console.error('Error checking session:', error);
});
}, []);
return (
<div className='Login-page'>
<h1>Login</h1>
<form onSubmit={login}>
<button type='submit' className='btn btn-outline-primary'>
Login
</button>
</form>
{loginStatus && <p>{loginStatus}</p>}
</div>
);
};
export default Login;
Server.js (Express file)
const express = require('express');
const app = express();
const mysql = require('mysql');
const morgan = require('morgan');
const cors = require('cors');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
// Middleware
app.use(cors({
origin: 'http://localhost:3000', // Replace with your frontend application's URL
methods: ["GET","POST","PUT", "DELETE"],
credentials: true, // Allow credentials (cookies)
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json()); // Parse JSON bodies
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies
app.use(morgan('dev')); // Use Morgan for logging HTTP requests
// Session setup
/* Set Cookie Settings */
app.use(
session({
secret: 'secretKey123',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // Set this to true if you use HTTPS
maxAge: 24 * 60 * 60 * 1000, // 24 hours
},
})
);
// Routes
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
connection.query(
'SELECT * FROM admin_users WHERE username = ? AND password = ?',
[username, password],
(error, results, fields) => {
if (error) {
console.error('Error executing MySQL query: ' + error.stack);
return res.status(500).json({ error: 'Internal Server Error' });
}
if (results.length > 0) {
req.session.username = username; // Set session variable to the username
res.json({ success: true, message: 'Login successful' });
} else {
res.json({ success: false, message: 'Invalid username or password' });
}
}
);
});
app.get('/check-session', (req, res) => {
if (req.session.username) {
res.json({ loggedIn: true, user: req.session.username });
} else {
res.json({ loggedIn: false });
}
});
app.post('/check-session', (req, res) => {
console.log(req.session)
if (req.session.isLoggedIn) {
res.json({ isLoggedIn: true });
} else {
res.json({ isLoggedIn: false });
}
});
app.post('/logout', (req, res) => {
req.session.destroy((error) => {
if (error) {
console.error('Error destroying session:', error);
return res.status(500).json({ error: 'Internal Server Error' });
}
res.clearCookie('userId'); // Clear the session cookie
res.json({ success: true, message: 'Logout successful' });
});
});
// Start the server
app.listen(5000, () => {
console.log('Server started on port 5000');
});
I have tried using Navigate to redirect but it does nothing. At this point anything would help. Ive tried following a Youtube guide but I ran into an issue with getting the session started. Now I have the session started but it fails to redirect.
2
Answers
You can’t Navigate like this in the latest version of react-router-dom (v6).
You have to follow these steps:
Now in the function, you have to create instance of it in the following way.
and, now you can redirect using this navigate.
Just replace your
return <Navigate to="/admin/home" />
with the
navigate("/admin/home)
You can refer this for more info: https://reactrouter.com/en/main/hooks/use-navigate
In your code, you’re checking first for "response.data.message"
And if there is a message, you just set the login status and do nothing!
When looking to Backend code, you’re always returning a message either it is a valid user/password or not.
This is why it does nothing. You need to check for something unique, "success" for example and also check that there is no "error", then redirect.