javascript - React: Is it ok to check cookies for refresh token?
问题描述
I have create a log in page, which has to enter username
and password
to authenticate. After the authentication, I push
the history
to the Homepage
by using react-router
and set a cookie
. The code is like:
const handleLogin = () =>{
const options = {
url: "http://test/login",
method: "POST",
withCredentials: true,
headers:{
"Accept": "application/json",
"content-Type": "application/json;charset-UTF-8"
},
data: {
"username": user,
"password": pass,
}
};
Axios(options).then(Response =>{
if(Response.data.JWT){
let decode = jwt_decode(Response.data.JWT);
if(decode.id){
setLoginUser(decode.username);
setAuthenticated(true);
history.push('/Homepage');
Cookies.set("isLogged", {expires: 1} )
}
}else{
alert("Invalid user");
}
});
}
I also used JWT from back-end, here the application is fine. But when I refresh the web page, I check through the cookies for the refresh token to stay in the Homepage, and remove it for log out.
const readCookie = () => {
let user = false;
if(user = Cookies.get("isLogged")){
history.push('/Homepage');
setAuthenticated(true);
}else{
history.push('/');
}
}
useEffect(() => {
readCookie()
},[]);
Is it OK to get refresh token like this?
解决方案
在外部,您的功能应该是您的useEffect
. 为避免这种情况,只需将其移入挂钩即可。除此之外,对我来说看起来不错。读取 cookie 是一种副作用,因此您的做法是正确的。
useEffect(() => {
const readCookie = () => {
let user = false;
if(user = Cookies.get("isLogged")){
history.push('/Homepage');
setAuthenticated(true);
}else{
history.push('/');
}
}
readCookie()
},[]);
如果您想离开readCookies
钩子,则必须将其包装在useCallback
钩子中并在依赖项中使用它,如下所示:
const readCookiesCallback = useCallback(() => {/* your read cookies code */}, [])
useEffect(() => {
readCookiesCallback()
}, [readCookiesCallback])
对于你正在做的事情,这是不必要的。我的第一个例子是要走的路。
推荐阅读
- python - 如何将 ORM 对象或此类对象列表与数据库“重新连接”?
- laravel - 在 Laravel 中哪里可以订阅 Redis Pub/Sub?
- typescript - 允许子类使用函数属性或方法覆盖
- java - 如何将 DefaultMutableTreeNode (Java) 序列化为 JSON?
- android - 使用 Intent 在活动之间传递字节数组时如何修复“致命异常”?
- api - 如何从“测试”包中测试 Golang 中的主包?
- php - 用php读取包含逗号的大型csv文件
- pyspark - 如何从 pyspark SparseVector 获取密钥
- angular - 如何从 API 接收 HTML 响应并将其绑定到 Angular 7 中的视图模板。
- jquery - Jquery动态添加行的复选框总是返回false