i am finding difficult to understand if when token is expired and logout action is performed, this last action is only executed when the page is refreshed. Although when token expire the 401 code is thrown it still make the protected route visible and only with a refresh it logs out and goes to login.. Is it supposed to be like this or should not be happening and i am missing something?
Here's the code in front
import React, { useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';
import {useDispatch} from 'react-redux'
import { logoutUser } from '../redux/ActionCreators';
import { baseUrl } from '../shared/baseUrl'
export const PrivateRoute = ({ component: Component, ...rest }) => {
const dispatch = useDispatch()
useEffect(() => {
// send jwt to API to see if it's valid
let token = localStorage.getItem("token");
if (token) {
fetch(baseUrl + "protected", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ token })
})
.then((res) => {
return res.json()
})
.then((json) => {
if (json.success) {
}
})
.catch((err) => {
dispatch(logoutUser())
})
} else {
dispatch(logoutUser())
}
}, [])
return (<Route {...rest} render={props => (
localStorage.getItem('token')
? <Component {...props} />
: <Redirect to={{ pathname: '/users/login', state: { from: props.location } }} />
)} />)
}
and the api called
protectedRouter.route('/')
.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200) })
.get(cors.cors, authenticate.verifyUser, authenticate.verifyAdmin, async (req, res, next) => {
res.statusCode = 403
res.end('Operation not supported')
})
.post(cors.corsWithOptions, async (req, res, next) => {
const token = req.body.token
if (token) {
try {
return jwt.verify(token, process.env.secretKey);
} catch (err) {
return null;
}
}
return null;
})
question from:
https://stackoverflow.com/questions/65928268/logout-when-token-expired-only-when-page-is-refreshed-why 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…