【问题标题】:Redirecting from getInitialProps in _error.js in nextjs?从 nextjs 中的 _error.js 中的 getInitialProps 重定向?
【发布时间】:2020-01-15 07:01:09
【问题描述】:

有什么方法可以从 nextjs 中的 _error.js 中的 getInitialProps 重定向到另一个 url?

已经在 getInitialProps 中尝试过 res.redirect('/');

它的给予 TypeError: res.redirect 不是函数

【问题讨论】:

    标签: next.js


    【解决方案1】:

    虽然我觉得这个来自_error.js 的重定向不太合适,但您可以尝试以下方法:

    import Router from 'next/router'
    
    // in your getInitialProps
    if (res) { // server
      res.writeHead(302, {
        Location: '/'
      });
    
      res.end();
    } else { // client
      Router.push('/');
    }
    

    由于getInitialProps 可能在导航到不同路线时在客户端上执行,因此您还应该考虑添加 else 情况。

    另外,我建议您重新考虑您的方法。 _error.js 用于处理 404 和 500 错误,您不需要在此级别进行重定向。


    如果您正在导入Error component_error.jsgetInitialProps 将不会被触发。

    【讨论】:

      【解决方案2】:

      试试这个?

      YourPage.getInitialProps = async (ctx) => {
        ctx.res.writeHead(302, {
          Location: '/some_url',
          'Content-Type': 'text/html; charset=utf-8',
        });
        ctx.res.end();
           
        return {};
      };

      【讨论】:

        猜你喜欢
        • 2021-09-15
        • 2020-07-13
        • 2020-04-08
        • 2021-06-23
        • 1970-01-01
        • 2021-10-31
        • 2018-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多