【问题标题】:How to redirect user to another page using getServerSideProps?如何使用 getServerSideProps 将用户重定向到另一个页面?
【发布时间】:2020-10-17 01:56:51
【问题描述】:

我找到了这个解决方案:

export const getServerSideProps = async ({ res }) => {
  res.redirect(301, '/another-page')
  
  return {
    props: {}
  }
}

但我在res 中没有看到redirect 方法并出现错误

【问题讨论】:

  • 您是否有条件地调用它而这只是伪代码?如果您想在每次反向代理或 CDN 重定向时都这样做,可能会更好地避免命中下一个 js

标签: reactjs react-router next.js


【解决方案1】:

好像您正在使用 Next.js。 试试这样的。

export const getServerSideProps = async ({ res }) => {
  res.setHeader("location", "/another-page")
  res.statusCode = 301
  res.end()
  return;
}

【讨论】:

    【解决方案2】:

    更简洁的方法如下所示:

    export const getServerSideProps = async ({ res }) => {
      res.writeHead(302, { Location: '//another-page/' });
      res.end()
      return;
    }
    

    我建议您使用状态码 302 而不是 301

    希望对你有帮助!

    【讨论】:

    • 为什么是 302 而不是 301?
    • 301 重定向意味着页面已永久移动到新位置。 302 重定向意味着移动只是暂时的。搜索引擎需要弄清楚是保留旧页面,还是将其替换为在新位置找到的页面。
    猜你喜欢
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2019-08-10
    • 2013-08-17
    相关资源
    最近更新 更多