在NextJS中从服务器端重定向 [英] Redirecting from server side in NextJS

查看:13
本文介绍了在NextJS中从服务器端重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Login.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)
  }
}  

server.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('/')
    }
}) 

推荐答案

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

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

这篇关于在NextJS中从服务器端重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆