在 NextJS 中从服务器端重定向

新手上路,请多包涵

我正在开发一个 Next.JS 应用程序,用户应该登录以查看内容。如果用户名和密码正确,我想将用户重定向到“/”。但是我的实现似乎不起作用。

我在 SO 上搜索了有关此的问题,但他们都在谈论使用 getInitialProps 进行重定向,但这对我没有帮助,因为我想从我的自定义快递服务器重定向用户。

登录.js

  async handleSubmit(event) {
  event.preventDefault()
  const { username, password } = this.state

  try {
    const response = await fetch('/log_in', {
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password })
    })
  }

 catch (error) {
    console.log(error)
  }
}

服务器.js

 app.post('/log_in', (req,res) => {
    console.log(`login form data`);
    console.log(`Username : ${req.body.username}`);
    console.log(`password : ${req.body.password}`);
    if(req.body.username == "user" && req.body.password == "123"){
        res.redirect('/')
    }
})

原文由 Pavindu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

这现在可以在 Next.js 10+ 上实现,而无需直接进行任何类型的响应头操作。如果满足您的条件,请使用 getServerSidePropsgetStaticProps 并返回 redirect 键作为唯一值:

 export async function getServerSideProps(context) {
  if(req.body.username == "user" && req.body.password == "123"){
    return {
      redirect: {
        permanent: false,
        destination: "/"
      }
    }
  }
}

原文由 bsplosion 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果可以的话,SEO 重定向服务器端是个好主意(不是像问题提到的登录)。

但是对于用户语言等,使用这样的服务器端重定向可能是个好主意。 ----- 已删除,因为它是错误的代码 ——–

更新,我最终得到了这个,因为我确实遇到了一些已经发送的标头的问题。请让我知道如何解决这个问题,因为它不是最理想的(尽管谷歌确实根据这篇文章理解它 https://www.seroundtable.com/google-meta-refresh-redirects-work-25335.html

 export default function HomePage({ language }) {
  return (
    <Head>
      <title>-</title>
      <meta httpEquiv="refresh" content={`0;url=/${language}/discover/0`} />
    </Head>
  );
}

更新 Nextjs 正在添加本机支持,有可用的 RFC: https ://github.com/vercel/next.js/discussions/17078

原文由 Richard Lindhout 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题