我目前在一个React项目中,我有一个使用令牌处理身份验证的后端,还有一个可以通过对服务器的异步调用对用户进行身份验证的React前端。
这就是我所拥有的:
这是我要实现的目标:
我当前的代码:
App.js
class App extends Component {
render() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/register">Register</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
<li>
<Link to="/TodoList">Protected Page</Link>
</li>
</ul>
<Route path="/register" component={Register} />
<Route path="/login" component={Login} />
<PrivateRoute path="/TodoList" component={TodoList} />
</div>
</Router>
);
}
}
PrivateRoute.js
import { verifAuth } from "./verifAuth";
class PrivateRoute extends Component {
state = {
loading: true,
isAuthenticated: false
};
componentDidMount() {
verifAuth().then(isAuthenticated => {
this.setState({
loading: false,
isAuthenticated
});
});
}
render() {
const { component: Component, ...rest } = this.props;
if (this.state.loading) {
return <div>LOADING</div>;
} else {
return (
<Route
{...rest}
render={props => (
<div>
{!this.state.isAuthenticated && (
<Redirect
to={{
pathname: "/login",
state: { from: this.props.location }
}}
/>
)}
<Component {...this.props} />
</div>
)}
/>
);
}
}
}
verifAuth.js
export async function verifAuth() {
return await axios
.post("/auth", {
token: localStorage.getItem("token")
})
.then(res => {
if (res.status === 200) return true;
return false;
})
.catch(err => console.log(err));
}
login.js中的重定向方法
const { from } = this.props.location.state || { from: { pathname: "/" } };
if (this.state.redirect) {
return <Redirect to={from} />;
}
答案 0 :(得分:0)
为此,我将使用React Router DOM,请遵循此文档https://reacttraining.com/react-router/web/example/auth-workflow,您将获得它!