[英]How to restrict user to display login page if already logged in using Reactjs
I am working on Reactjs and using nextjs framework, I am working on "Login Logout" module and i just want that if user already logged in ( email set in cookie) then he should redirect to "dashboard" page,How can i do this?我正在研究 Reactjs 并使用 nextjs 框架,我正在研究“登录注销”模块,我只希望如果用户已经登录(cookie 中设置了 email),那么他应该重定向到“仪表板”页面,我该怎么做? I tried with following code but not working for me, giving me error ",Here is my current code我尝试使用以下代码但不适合我,给我错误“,这是我当前的代码
cookies returned from getServerSideProps Reason: undefined cannot be serialized as JSON
export async function getServerSideProps(context: { req: { headers: { cookies: any; }; }; }) {
const cookies = context.req.headers.cookies;
if (cookies && cookies.email) {
// email is present in cookies, so redirect to /dashboard
return {
redirect: {
destination: "/dashboard",
statusCode: 302, // temporary redirect
},
props: {},
};
}
return {
props: {
cookies,
},
};
}
When returning props.cookies
from getServerSideProps
, you are potentially returning the cookies as undefined
.从getServerSideProps
返回props.cookies
时,您可能会将 cookies 返回为undefined
。 Use ''
as the default value if missing.如果缺少,请使用''
作为默认值。
You can do this:你可以这样做:
return {
props: {
cookies: cookies || '',
},
};
You need to parse the cookies and you can get the cookies on the request you don't need the header您需要解析 cookies 并且可以根据不需要 header 的请求获得 cookies
const cookies = JSON.parse(context.req.cookies);
if(cookies.email !== undefined)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.