处理登录页面get请求的路由检查用户是否已经登录。如果是,则将其重定向到/userprofile,如果不是,则呈现登录。ejs观点。
从我读到的,res.redirect()应该结束http请求,但在这个例子中,我得到了一些奇怪的行为。当用户登录时,我得到错误"发送到客户端后无法设置标头"很多次了。下面是代码:
app.get("/login", (req, res) => {
if (req.session.user) { res.redirect('/userprofile') };
res.render('login');
})
但是我意识到如果
- 我只是在res.redirect()或 之前包含一个返回值
- 否定if语句并反转响应顺序
代码运行正常
有人能解释为什么吗?由于
这是由于您在呈现登录之前将用户重定向到/userprofile
造成的。你可以避免这种情况的一种方法是在fetch中做重定向前端。
fetch('login', {
method: 'POST',
})
.then(() => {
window.location.href = '/userprofile'
})