我从另一个具有文件LoggedIn()的文件名Auth.js导入Auth类,当凭据为true时此函数返回true,否则返回false,但是当调用它时凭据正确时返回undefined,但是如果凭据正确是不正确的,它会退后
要登录但没有重定向,我希望它重定向,当Authed.LoggedIn()返回true时可以实现
// exported file
import Axios from 'axios'
import decode from 'jwt-decode'
export default class Auth {
LoggedIn = () => {
if(localStorage.getItem("token")){
const data = decode(localStorage.getItem("token"))
Axios.post(`http://localhost:4000/check`,{token : localStorage.getItem('token')})
.then((res) => {
if(data.password === res.data.password){
console.log('In Log')
return true
}
else{
console.log('Not Log')
return false
}
})
}
else{
console.log('Not 1 Log')
return false
}
}
};
// File in Use
import React from 'react'
import { BrowserRouter as Router, Route, Link, Redirect } from "react-router-dom";
import Login from './Login';
import AddEmployee from './AddEmployee'
import Header from './Header';
import SearchTable from './SearchTable';
import Main from './Main';
import ManageConfig from './ManageConfig'
import Com from './Com'
import Radio from './Radio';
import Antenna from './Antenna';
import Network from './Networks';
import Auth from './AUTH'
const Authed = new Auth()
console.log(Authed.LoggedIn()) // return undefined if LoggedIn else
// return false
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render = {props =>
Authed.LoggedIn() ? (
<Component {...props} />
) : (
<Redirect
to="/"
/>
)
}
/>
);
const Routes = () => {
return (
<Router>
<Route exact path='/' component={Login} />
<Route path='/addEmployee' component={AddEmployee} />
<Route path='/search' component={SearchTable} />
<PrivateRoute path='/config/managefreq' component={Main} />
<PrivateRoute path='/config/managecom' component={Com} />
<PrivateRoute path='/config/manageradio' component={Radio} />
<PrivateRoute path='/config/manageantenna' component={Antenna} />
<PrivateRoute exact path='/config' component={ManageConfig} />
<PrivateRoute exact path='/manageNets' component={Network} />
</Router>
)
}
export default Routes
如果已登录,则返回True