0

当用户未通过身份验证时,我一直在尝试几种方法来保护路由,但到目前为止我一直在努力解决这个问题。

尝试从 getServerSideProps 进行身份验证时最常出现的问题是我经常遇到 a Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client,所以我一直试图不从那里重定向并设置一个redirect布尔值,以便我可以从客户端重定向。问题是现在我得到一个错误,No router instance found. you should only use "next/router" inside the client side of your app.即使我(我认为)在客户端。

export async function getServerSideProps(ctx: ApiRoutesTypes) {

  const cookie = parseCookies(ctx);

   if (!testCookie.autho) {
     const redirectLogin = true;

     return { props: { redirectLogin } };
   }

  const query = {
    text: 'SELECT fk_users_id FROM tokens WHERE token = $1 AND status = true',
    values: [cookie],
  };
  const userId = (await db.query(query)).rows[0].fk_users_id;
    ...

  return { props: { userId } };
}
export default function Homepage({redirectLogin }){
  const router = useRouter();

  
  if (redirectLogin) {
    router.push('/login');
  }

    ...

}

有可能解决这个问题吗?如果不是,如果我的所有页面都大量使用 getServerSideProps 但还需要进行身份验证,那么重定向的最佳方法是什么?

4

1 回答 1

1

使用受保护路由并将用户重定向到登录页面的最佳方法-

使用函数来设置页面的初始道具 - 现在如果调用函数时通过页面是否受保护。

export const authInitialProps = isProtectedRoute => ({
  req,
  res,
  query: { userId }
}) => {
  const auth = req ? getSessionFromServer(req) : getSessionFromClient();
  const currentPath = req ? req.url : window.location.pathname;
  const user = auth.user;
  const isAnonymous = !user;
  if ( isProtectedRoute && isAnonymous && currentPath !== "/signin") {
    return redirectUser(res, "/signin");
  }
  return { auth, userId };
};

这里 isProtectedRoute 将告诉您路由是否受保护。如果是这样,并且用户未登录或未登录。如果不是 - 那么。

将用户重定向到新页面,即登录。

如果登录- 那么

将身份验证数据传递到页面。

现在检查用户是否登录?

  1. 服务器端检查-
export const getSessionFromServer = req => {
  if (req.user) {
    return { user: req.user };
  }
  return {};
};
  1. 客户端检查-
Use cookies or local storage, whatever is being used by you.
To check for the login.
于 2020-08-31T19:17:42.760 回答