我正在开发一个 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 许可协议
这现在可以在 Next.js 10+ 上实现,而无需直接进行任何类型的响应头操作。如果满足您的条件,请使用
getServerSideProps
或getStaticProps
并返回redirect
键作为唯一值: