This is my first question.
I am self-studying React.js, Node.js, and Express. For this reason, I am trying to create my own website where a user can register, log in, and access the page with their data only if the login is successful.
If the login is successful, a token is created using the user’s email as the payload. Additionally, I want to use a Higher Order Component (HOC) called Protect so that in my App.js file, I have something like:
<Route
path="/ProtectedPage"
element={<Protect component={<ProtectedPage />} />}
/>
In the handleFormSubmit function of FormLogin, I added
navigate('/ProtectedPage');
But even if the login is successful, I don’t get any errors or redirection. It might be useful to know that Protected makes a GET request to
const verifyToken = (req, res, next) => {
const token = req.cookies.token;
if (!token) {
res.status(401).send('Access Denied');
} else {
jwt.verify(token, secret, function (err, decoded) {
if (err) {
res.status(401).send('No Valid Token!');
} else {
req.email = decoded.email;
req.token = token;
console.log('verifyToken: ', req.email);
next();
}
});
}
};
app.get('/checkAuth', verifyToken, (req, res) => {
res.sendStatus(200).send({ authenticated: true, email: req.email, token: req.token});
});
Protected.js
import React, { useState, useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import axios from 'axios';
const Protect = ({ component: Component }) => {
const [authenticated, setAuthenticated] = useState(false);
useEffect(() => {
// Funzione per verificare l'autenticazione
const checkAuth = async () => {
try {
// Chiamata API per verificare l'autenticazione
const response = await axios.get('http://localhost:5000/checkAuth', { withCredentials: true });
console.log('CheckAuth Response:', response);
// Se l'autenticazione è riuscita, imposta lo stato a true
if (response.status === 200) {
setAuthenticated(true);
} else {
setAuthenticated(false);
}
} catch (error) {
console.error('Protect: Errore durante la verifica dell'autenticazione', error.response);
setAuthenticated(false);
}
};
// Chiamare la funzione di verifica dell'autenticazione al caricamento del componente
checkAuth();
}, []);
// Se l'autenticazione è avvenuta con successo, rendi il componente interno
// Altrimenti, reindirizza a /Login
return authenticated ? <Component /> : <Navigate to="/Login" />;
};
export default Protect;
You can view my code at this link: https://github.com/CiccioLagXCVIII/MyOwnSite.git
I have already tried using console.log to verify if the data is received and sent correctly, and it is. My issue is that I don’t see any errors in the console when the login is successful, but the redirection doesn’t happen.