错误:在node.js中使用express从localhost重定向的次数太多

错误:在node.js中使用express从localhost重定向的次数太多,node.js,express,response.redirect,Node.js,Express,Response.redirect,我是node.js的新手,如果没有登录,我会尝试在localhost:4000/之后重定向所有路由。它给了我太多重定向的错误 我在app.js中使用app.get的代码 app.get('*', loggedInCheck); 下面的代码是我写的loggedInCheck函数 function loggedInCheck(req, res, next) { if (req.isAuthenticated()){ res.redirect('/status'); }else{

我是node.js的新手,如果没有登录,我会尝试在localhost:4000/之后重定向所有路由。它给了我太多重定向的错误

我在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');

  }
}
然而,它一直给我一个错误,因为太多的重定向,并没有通过登录页面,因为它还没有验证

我这里有什么问题?我怎样才能解决这个问题

有人能帮我吗

以防万一,我将把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();
   }
});

我看不出您的代码在哪里使用应用程序。请使用“*”@ExplosionPills-oops。对不起,我粘贴了以前的代码。我刚刚编辑过。谢谢