【问题标题】:Prev page URL when I am redirecting in getServerSideProps (Next.js)当我在 getServerSideProps (Next.js) 中重定向时的上一页 URL
【发布时间】:2021-03-17 09:59:56
【问题描述】:

我对 Next.js 和所有这些 SSR 东西还是很陌生,所以我需要一个建议。 这是我的情况:

我在 auth 后面有一个页面,我正在尝试做一些预取:

export const getServerSideProps: GetServerSideProps<SomeProps> = async ({ req, res }) => {
  try {
    const data = await fetchOnServerSide<Data[]>(someAPI, req, {
      method: 'GET',
    });
    return {
      props: data, // will be passed to the page component as props
    };
  } catch (error) {
    // Oops, you aren't authed for doing it or your token expired -> go to the "login page"
    if (res) {
      res.writeHead(302, { Location: '/login' });
      res.end();
    }
    return { props: {} };
  }
};

它有效,但我想在成功验证后将我的用户从登录页面重定向回来。 在这种情况下如何获取上一页 URL?

【问题讨论】:

  • 到目前为止您尝试过什么?您的登录页面是什么样的?
  • 我试过 Router.back() 但它只适用于客户端重定向。现在我只需在主页上使用 router.push('/'); 重定向用户;

标签: javascript redirect next.js


【解决方案1】:

您可以在重定向时将当前页面作为查询参数发送到登录页面。然后,在您的登录页面中,一旦登录成功,您就可以重定向回它。

export const getServerSideProps: GetServerSideProps<SomeProps> = async ({ req }) => {
    try {
        const data = await fetchOnServerSide<Data[]>(someAPI, req, { method: 'GET' });
        return {
            props: data
        };
    } catch (error) {
        return { 
            redirect: {
                destination: '/login?from=current-page', // Replace `current-page` with the actual page
                statusCode: 302,
            } 
        };
    }
};

我建议您从 getServerSideProps 返回 redirect 对象,而不是调用 res.writeHead 以获得更惯用的方法。

【讨论】:

    猜你喜欢
    • 2022-08-20
    • 2021-04-23
    • 2021-08-04
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多