这是向/loginCheck 路由发送获取请求的客户端代码。
console.log("In user login checking function");
readAllData('loginDetail')
.then(function(loginDetails){
console.log(JSON.stringify(loginDetails[0]));
return fetch('/loginCheck', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(loginDetails[0])
})
.then(function(res){
console.log(res.status);
})
.catch(function(err){
console.log(err);
})
});
这是服务器端代码,用于检查用户是否已登录以及我是否想重定向到 main.html 页面。
app.post('/loginCheck', (req, res)=>{
const userName=req.body.nickName;
console.log(userName);
Detail.findOne({nickName:userName}, function(err, docs){
if(err){
console.log(err);
}else{
console.log("Inside else");
if(!docs){
res.redirect('/');
}else{
isLogged=true;
console.log(isLogged);
console.log("Redirecting to the main page");
res.redirect('/main.html');
}
}
})
});
日志语句正在执行,但重定向不起作用。有人可以指出出了什么问题吗?
最佳答案
您必须在客户端而不是服务器端执行重定向代码。
这是正确的代码
console.log("In user login checking function");
readAllData('loginDetail')
.then(function(loginDetails){
console.log(JSON.stringify(loginDetails[0]));
return fetch('/loginCheck', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(loginDetails[0])
})
.then(function(res){
console.log(res.status);
if (res.status == true){
location.href = '/main.html';
} else {
location.href = '/';
}
})
.catch(function(err){
console.log(err);
})
});
//Here is the server side code that checks if the user is logged in and if he is i want to redirect to the main.html page.
app.post('/loginCheck', (req, res)=>{
const userName=req.body.nickName;
console.log(userName);
Detail.findOne({nickName:userName}, function(err, docs){
if(err){
res.json({ status: false});
console.log(err);
}else{
console.log("Inside else");
if(!docs){
res.json({ status: false});
}else{
let isLogged=true;
console.log(isLogged);
res.json({ status: true});
}
}
})
});
关于node.js - 如果用户已登录,则希望重定向该用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64149749/