我无法理解为什么我的Authorized
vsUnauthorized
路由运行不正常.. 以下是我的路由设置方式:
class App extends Component {
render() {
return (
<HashRouter>
<React.Suspense fallback={loading()}>
<Switch>
<UnauthenticatedRoute exact path="/login" name="Login Page" component={Login} />
<Route exact path="/register" name="Register Page" component={Register} />
<Route exact path="/404" name="Page 404" component={Page404} />
<Route exact path="/500" name="Page 500" component={Page500} />
<AuthenticatedRoute path="/" name="Home" component={DefaultLayout} />
</Switch>
</React.Suspense>
</HashRouter>
);
}
}
export default App;
我有一个auth.js
包含所有这些路由类型以及检查 JWT 令牌是否有效的方法:
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { Api } from './api'
const isAuthenticated = () => {
Api.isActiveToken(sessionStorage.getItem('token')).then(
(response) => {
console.log(response)
return response.ok
},
(error) => {
return false
}
)
}
const AuthenticatedRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated()
? <Component {...props} />
: <Redirect to='/login' />
)} />
);
const UnauthenticatedRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
!isAuthenticated()
? <Component {...props} />
: <Redirect to='/' />
)} />
);
export { AuthenticatedRoute, UnauthenticatedRoute }
凡console.log(response)
看来,这样的:
Response {type: "cors", url: "http://xxx/api/v1/login/validate-token", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://xxx/api/v1/login/validate-token"
__proto__: Response
我sessionStorage
拿着令牌就好了。我做错了什么,以至于我的路线永远不会重定向/允许我转到AuthorizedRoute
?