You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在getServerSideProps中调用useRouter报错,求token过期重定向方案

实现Token过期时重定向到登录页的正确方式

你的需求完全可以实现,但不能在getServerSideProps中使用useRouter——因为getServerSideProps是Next.js的服务器端数据获取函数,并非React组件或自定义Hook,不符合React Hook的调用规则,这就是你报错的原因。

正确的做法是利用Next.js为getServerSideProps提供的重定向返回值,具体步骤如下:

  1. 移除useRouter的调用,它在服务器端函数中完全无效
  2. 捕获到401未授权错误时,返回包含redirect属性的对象,Next.js会自动处理重定向逻辑
  3. 确保getServerSideProps始终返回符合要求的结构(成功时返回props,重定向时返回redirect)

修改后的代码示例:

export async function getServerSideProps({ req, params }) {
  const token = await getToken({ req });
  const userId = params.userId;

  try {
    const res = await axiosPrivateWithToken(token).get(`/user/${userId}`);
    // 请求成功,返回数据作为页面props
    return {
      props: { userData: res.data }
    };
  } catch (error) {
    if (error.response?.status === 401) {
      // Token过期/未授权,触发重定向到登录页
      return {
        redirect: {
          destination: '/login',
          permanent: false // 临时重定向,使用302状态码
        }
      };
    }
    // 处理其他错误情况,返回默认props或错误信息
    return {
      props: { userData: null, error: '数据请求失败' }
    };
  }
}

关键细节说明:

  • redirect对象中permanent设为false是登录场景的合理选择,避免浏览器缓存重定向规则
  • 改用try/catch替代.then/.catch,让异步代码逻辑更直观易读
  • 修正了原代码中accessToken的变量名错误(应为获取到的token)

内容的提问来源于stack exchange,提问作者Paul Last

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:55:25