![](/img/trans.png)
[英]Angular 2/4: How to restrict access to Login Route if user is already logged in?
[英]How to restrict user to display login page if already logged in using Reactjs
我正在研究 Reactjs 並使用 nextjs 框架,我正在研究“登錄注銷”模塊,我只希望如果用戶已經登錄(cookie 中設置了 email),那么他應該重定向到“儀表板”頁面,我該怎么做? 我嘗試使用以下代碼但不適合我,給我錯誤“,這是我當前的代碼
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,
},
};
}
從getServerSideProps
返回props.cookies
時,您可能會將 cookies 返回為undefined
。 如果缺少,請使用''
作為默認值。
你可以這樣做:
return {
props: {
cookies: cookies || '',
},
};
您需要解析 cookies 並且可以根據不需要 header 的請求獲得 cookies
const cookies = JSON.parse(context.req.cookies);
if(cookies.email !== undefined)...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.