0

我在前端使用 NextJS,在后端使用 NodeJS(Express)。我尝试使用getServerSideProps来检查和预渲染用户是否经过身份验证,但它不起作用。我尝试添加credentials: 'include',但它也没有工作

export async function getServerSideProps(context) {
  
  const response = await fetch('http://localhost:3000/api/auth/user', {
    method: 'GET',
    credentials: 'include',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json',
    },
  });

  if (response.status === 401) {
    return {
      props: { data: null },
    };
  }
  const result = await response.json();
  return {
    props: {
      data: result,
    },
  };
}

错误:

  • url: 'http://localhost:3000/api/auth/user',
  • 状态:401,
  • statusText: '未授权',
  • headers: Headers { [Symbol(map)]: [Object: null prototype] },
  • 计数器:0

我知道客户端使用useEffect()可能会解决问题,但我不想在渲染完成后看到状态变化。

例如:在我的导航栏中,如果用户已通过身份验证,则应显示username,如果不是,则仅显示“登录”。但是每次我刷新它都会首先显示“登录”,然后几秒钟后它会变成username(假设用户已登录)。

还有其他方法吗?

谢谢!

4

0 回答 0