在 NextJS 中从服务器端重定向

Pav*_*ndu 15 reactjs next.js

我正在开发一个 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)
  }
}  
Run Code Online (Sandbox Code Playgroud)

服务器.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('/')
    }
}) 
Run Code Online (Sandbox Code Playgroud)

bsp*_*ion 26

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

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

  • 值得一提的是,要实现这一点,Next 还需要默认导出页面组件。例如,`导出默认函数 Redirect() { }` (4认同)

Ric*_*out 5

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

但是对于像用户语言等这样的东西,使用这样的服务器端重定向可能是个好主意。

export const getServerSideProps = async ({ req, res }) => {
if (res) {
    res.writeHead(302, { // or 301
      Location: "localized/url/product/categories",
    });
    res.end();
  }
}
Run Code Online (Sandbox Code Playgroud)

更新,我最终得到了这个,因为我已经发送的标头确实有一些问题。请让我知道如何解决这个问题,因为它不是最理想的(尽管谷歌确实根据这篇文章理解它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>
  );
}
Run Code Online (Sandbox Code Playgroud)

更新 Nextjs 正在添加原生支持,有一个 RFC 可用:https : //github.com/vercel/next.js/discussions/17078