【发布时间】:2019-12-03 16:07:41
【问题描述】:
我有一个后端 API,我可以向其发送电子邮件和密码。作为回报,它会在成功认证后提供一个认证令牌。我已经在文件 auth.js 中编写了用于发送此 API 请求的代码。它看起来像这样:
import axios from "axios";
export const auth = {
isAuthenticated: false,
login(user) {
const config = {
headers: {
"Content-Type": "application/json"
}
};
const body = JSON.stringify({ email: user.email, password: user.password });
return axios
.post("http://localhost:5000/userauth/login", body, config)
.then(res => {
localStorage.setItem("token", res.data.token);
this.isAuthenticated = true;
return res.data;
})
.catch(err => {
this.isAuthenticated = false;
console.log(err);
});
}
};
我在 App.js 中调用 auth。在这个 I 文件中,我有一个私有路由“/dashboard”,只有在身份验证后才能访问。如果未通过身份验证,它会重定向到“/login”路由。
这是它的代码:
import { auth } from "./actions/auth";
// rest of imports ...
export default function App() {
return (
<Router>
<Route path="/" exact component={Home} />
<Route path="/login" component={Login} />
<PrivateRoute path="/dashboard" component={Dashboard} />
</Router>
);
}
// ... ...
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
auth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
另外,我的登录表单的 onSubmit 函数如下所示:
onSubmit(e) {
e.preventDefault();
const user = {
email: this.state.email,
password: this.state.password
};
auth.login(user).then(res => {
if (res) {
this.props.history.push("/dashboard");
}
});
}
现在每当我在登录表单中输入正确的email 和password 时,我都会成功重定向到/dashboard 路由。但是如果我在登录后重新加载/dashboard 路由,它会再次将我发送回登录页面。
据我了解,它应该留在仪表板页面上,因为登录后isAuthenticated 设置为 true。
因此我的私人路线应该有效。那我错过了什么?另外作为记录,我正在关注 this 创建 PrivateRoute 的教程。
【问题讨论】:
标签: reactjs asynchronous react-router