Error: TOO_MANY_REDIRECTS from localhost using express in node.js

Error: TOO_MANY_REDIRECTS from localhost using express in node.js

我是 node.js 的新手,如果未登录,我正在尝试重定向 localhost:4000/ 之后的所有路由。它给我错误 "Too many redirects"...

我在 app.js

中使用 app.get 的代码
app.get('*', loggedInCheck);

下面的代码是我写的loggedInCheck函数,

function loggedInCheck(req, res, next) {
  if (req.isAuthenticated()){
    res.redirect('/status');

  }else{
    console.log("Please Log in to access to this webpage");
    res.redirect('/login');

  }
}

但是,它一直给我一个错误 "Too many redirects" 并且没有通过登录页面,因为它还没有通过身份验证。

我的问题是什么?我该如何解决这个问题....?

有人可以帮我吗??

为了以防万一,我会把我的整个代码从 app.js

app.js

var io = require('socket.io');
var express = require('express');
var app = express();
var redis = require('redis');
var sys = require('util');
var fs = require('fs');
//Added for connecting login session
var http = require('http');
var server = http.createServer(app);
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

//Connecting Database (MongoDB)
mongoose.connect("my private mongoDB address");
var db = mongoose.connection;
db.once("open",function () {
  console.log("DB connected!");
});
db.on("error",function (err) {
  console.log("DB ERROR :", err);
});

//Setting bcrypt for password.
var bcrypt = require("bcrypt-nodejs");

//Setting userSchema for MongoDB.
var userSchema = mongoose.Schema({
  email: {type:String, required:true, unique:true},
  password: {type:String, required:true},
  createdAt: {type:Date, default:Date.now}
});
userSchema.pre("save", function (next){
  var user = this;
  if(!user.isModified("password")){
    return next();
  } else {
    user.password = bcrypt.hashSync(user.password);
    return next();
  }
});

//setting bcrypt for password.
userSchema.methods.authenticate = function (password) {
  var user = this;
  return bcrypt.compareSync(password,user.password);
};

//Setting User as userSchema.
var User = mongoose.model('user',userSchema);

io = io.listen(server);

//Setting middleware for login format.
app.set("view engine", 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(flash());

app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());

//Initializing passport.
passport.serializeUser(function(user, done) {
  //console.log('serializeUser()', user);
  done(null, user.id);
});
passport.deserializeUser(function(id, done) {
  //console.log('deserializeUser()', user);
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

var global_username = '';         //Global variable for username to put in the address

//Initializing passport-local strategy.
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-login',
  new LocalStrategy({
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true
    },
    function(req, email, password, done) {
      User.findOne({ 'email' :  email }, function(err, user) {
        if (err) return done(err);
        if (!user){
            req.flash("email", req.body.email);
            return done(null, false, req.flash('loginError', 'No user found.'));
        }
        if (!user.authenticate(password)){
            req.flash("email", req.body.email);
            return done(null, false, req.flash('loginError', 'Password does not Match.'));
        }
        var email_address = req.body.email;
        var username = email_address.substring(0, email_address.lastIndexOf("@"));
        global_username = username;
        return done(null, user);
      });
    }
  )
);

//Check whether it is logged in or not.
//If it is not logged in(Session is out), it goes to login page
//If it is logged in(Session is still on), it goes directly to status.html
app.get('*', loggedInCheck);

app.get('/login', function (req,res) {
  res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
});

//Accessing to MongoDB to check to login or not
app.post('/login',
  function (req,res,next){
    next();
  }, passport.authenticate('local-login', {
    successRedirect : '/status',
    failureRedirect : '/login',
    failureFlash : true
  })
);

//Logging out
app.get('/logout', function(req, res) {
    req.logout();
    console.log("Logging out the account!");
    res.redirect('/login');
});

//Creating new account
app.get('/users/new', function(req,res){
  res.render('users/new', {
                            formData: req.flash('formData')[0],
                            emailError: req.flash('emailError')[0],
                            passwordError: req.flash('passwordError')[0]
                          }
  );
});

//If creating an account is successed, then goes back to login page.
app.post('/users', checkUserRegValidation, function(req,res,next){
  User.create(req.body.user, function (err,user) {
    if(err) return res.json({success:false, message:err});
    res.redirect('/login');
  });
});

//Calling status.html
app.get('/status', isLoggedIn, function(req, res){
  res.redirect('/status.html?channel=' + global_username);
});

//Calling Topology_view html
app.get('/topology', isLoggedIn, function(req, res){
  console.log("Accessing to topology_view");
  res.redirect('topology.html?channel=' + global_username);
});

//functions
//Check whether session is still on or not.
function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()){
    console.log("Authenticated");
    return next();

  }else{
    console.log("Unauthorized Attempt");
    res.redirect('/login');
  }
}

//Initial checking whether session is on or not.
function loggedInCheck(req, res, next) {
  if (req.isAuthenticated()){
    res.redirect('/status');

  }else{
    console.log("Please Log in to access to this webpage");
    res.redirect('/login');

  }
}

//Checking whether email is already in the database or not in sign up.
//If email is already in the database, it gives error message.
function checkUserRegValidation(req, res, next) {
  var isValid = true;

  async.waterfall(
    [function(callback) {
      User.findOne({email: req.body.user.email, _id: {$ne: mongoose.Types.ObjectId(req.params.id)}},
        function(err,user){
          if(user){
            isValid = false;
            req.flash("emailError","- This email is already resistered.");
          }
          callback(null, isValid);
        }
      );
    }], function(err, isValid) {
      if(err) return res.json({success:"false", message:err});
      if(isValid){
        return next();
      } else {
        req.flash("formData",req.body.user);
        res.redirect("back");
      }
    }
  );
}

//handler function is for topology.html.
function handler(req,res){
        fs.readFile(__dirname + '/public/topology.html', function(err,data){
                if(err){
                        res.writeHead(500);
                        return res.end('Error loading topology.html');
                }

                res.writeHead(200);
                console.log("Listening on port 3000");
                res.end(data);
        });

        fs.readFile(__dirname + '/public/style.css', function(err,data){
                if(err){
                        res.writeHead(500);
                        return res.end('Error loading topology.html');
                }

                res.writeHead(200);
                console.log("Listening on port 3000");
                res.end(data);
        });
}

io.sockets.addListener('connection', function(socket){
    console.log("connceted : " + socket.id);

    var subscriber = redis.createClient(6379, 'localhost');
    subscriber.psubscribe("*");
    subscriber.on("pmessage", function(pattern, channel, message) {
        //console.log(message);
        socket.emit(channel, message);
    });

    socket.on('disconnect', function () {
        console.log("disconnceted : " + socket.id);
        subscriber.quit();
    });

    socket.on('close', function() {
        console.log("close");
        subscriber.quit();
    });
});

server.listen(4000);

您的问题出在您的 loggedInCheck 函数中。无论您在哪条路线上,您都在检查用户是否已通过身份验证,否则将重定向到登录。因此,即使您试图进入登录页面,它也会尝试重新定向,并且永远重复。

app.get('*', loggedInCheck);

这不是一个好方法。你应该有某种功能来确保你不会试图去一个对非用户来说没问题的区域。也许是这样的:

app.get('*', function(req, res, next){
   if(req.url != '/login'){
      loggedInCheck(req, res, next);
   }else{
      next();
   }
});