node.js - 如果用户已登录,则希望重定向该用户

标签 node.js express redirect routes fetch

这是向/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/

相关文章:

Node.js 流管道和垃圾收集

mysql - SequelizeEagerLoadingError : (parent) is not associated to (child)!

mysql - sql 查询回调中的 res.sendFile

ruby-on-rails - 如何在路由级别重定向,而不是在操作级别?

.htaccess 重定向后隐藏子目录 url

java - 如何根据包有选择地将system.out重定向到文件

node.js - 如何使用 PM2 运行多个 package.json 脚本之一?

javascript - 将 Meteor 与 Adob​​e Flash CreateJS 工具包一起使用

TypeScript Express 错误函数

javascript - 如何在 node.js 中的 for 循环中编写回调函数