如何在node.js中使用express.static显示index.html之前显示login页面

我正在使用app.use(express.static(path.join(__dirname,'public'))); 在显示Node.js中的index.html之前显示login页面

但是,它不显示index.html之前的login页面…我试图使用app.get('/', function (req,res) {res.redirect('/login');}); 但它甚至不通过该app.get ,并且在连接到localhost时不redirect:4000 …

我的目录设置如下所示

 myapp node_modules public images javascripts js stylesheets index.html routes views login login.ejs users new.ejs index.jade layout.jade app.js package.json 

此外,我想在公共文件夹中保存index.html,只是想在之前显示login页面。有没有什么方法来显示?

这是我在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 mongoose.connect("my mongoDB private address"); var db = mongoose.connection; db.once("open",function () { console.log("DB connected!"); }); db.on("error",function (err) { console.log("DB ERROR :", err); }); var bcrypt = require("bcrypt-nodejs"); 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(); } }); userSchema.methods.authenticate = function (password) { var user = this; return bcrypt.compareSync(password,user.password); }; var User = mongoose.model('user',userSchema); io = io.listen(server); app.set("view engine", 'ejs'); app.use(express.static(path.join(__dirname, 'public'))); //setting middleware for login 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()); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); 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.')); } return done(null, user); }); } ) ); //set home routes //var data_1 = {email:''}; app.get('/', function (req,res) { res.redirect('/login'); //req.url = '/login'; //next(); }); app.get('/login', function (req,res) { res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')}); }); app.post('/login', function(req, res, next) { passport.authenticate('local-login', function(err, user, info) { if (err) { return next(err); } if (!user) { return res.redirect('/login'); } return res.redirect('/?channel='+ req.body.email); })(req, res, next); }); app.get('/logout', function(req, res) { req.logout(); res.redirect('/login'); }); // set user routes 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] } ); }); // new 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'); }); }); // create //functions function isLoggedIn(req, res, next) { if (req.isAuthenticated()){ return next(); }else{ res.redirect('/login'); } res.redirect('/'); } 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"); } } ); } function handler(req,res){ console.log(req); fs.readFile(__dirname + '/public/index.html', function(err,data){ if(err){ res.writeHead(500); return res.end('Error loading index.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 index.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(); }); }); app.listen(4000, function(){ console.log('Server On!!!'); }); 

我应该使用另一个快递显示login页面? 或者我应该在这里做什么? 我实际上是node.js中的新手

任何人都可以帮我在这里?

谢谢..

编辑:我的app.js的整个代码

 var express = require('express'); var app = express(); //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 cookieParser = require('cookie-parser'); var methodOverride = require('method-override'); //connecting database mongoose.connect("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); }); var bcrypt = require("bcrypt-nodejs"); 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(); } }); userSchema.methods.authenticate = function (password) { var user = this; return bcrypt.compareSync(password,user.password); }; var User = mongoose.model('user',userSchema); app.set("view engine", 'ejs'); app.use(express.static(path.join(__dirname, 'public'))); //setting middleware for login app.use(cookieParser()); 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()); 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 = ''; 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); }); } ) ); //set home routes app.get('*', loggedInCheck); ------------------>This is the code with loggedInCheck function. I created another one instead of isLoggedIn function app.get('/login', function (req,res) { res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')}); }); app.post('/login', function (req,res,next){ next(); }, passport.authenticate('local-login', { successRedirect : '/posts', failureRedirect : '/login', failureFlash : true }) ); app.get('/logout', function(req, res) { req.logout(); res.redirect('/login'); }); // set user routes 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] } ); }); // new 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'); }); }); // create app.get('/posts', isLoggedIn, function(req, res){ res.redirect('/status.html?channel=' + global_username); }); //functions function isLoggedIn(req, res, next) { if (req.isAuthenticated()){ console.log("Authenticated"); console.log("Accessing to status.html"); return next(); }else{ console.log("Unauthorized Attempt"); res.redirect('/login'); } } function loggedInCheck(req, res, next) { if (req.isAuthenticated()){ res.redirect('/status.html?channel=' + global_username); }else{ console.log("Unauthorized Attempt"); res.redirect('/login'); } } server.listen(5000); 

在Express中,通话顺序很重要。

在你的情况下,对app.use (express.static... )的调用是在app.get ('/'...之前完成的,所以它具有更高的优先级,而且由于express.static结束了中间件链,永远不要打电话给你的app.get

一个可能的解决scheme是将app.get放在app.get之上app.use (express.static

但是,如果你这样做,你将永远无法显示你的index.html 。 您可以添加一个条件来select是redirect到/login还是调用next ()来继续中间件链。

编辑

在深入了解你的代码后,你似乎有一个中间件isLoggedIn做适当的逻辑。

您可以保持中间件的顺序不变,并执行app.get('*', isLoggedIn);

这将调用您的中间件的任何GET请求。

嗨,我把你的app.js文件分成多个部分,以便隔离路由器,这些文件在下面给出。

app.js

 var express = require('./express'), mongoose = require('./mongoose'), passport = require('./passport'); var db = mongoose(); var app = express(); var passport = passport(); app.listen(3000, function() { console.log('Server running on port: ' + 3000); }); 

express.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'); module.exports = function() { io = io.listen(server); app.set("view engine", 'ejs'); app.use(express.static(path.join(__dirname, 'public'))); //setting middleware for login 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()); require('./passport'); require('./router')(app); 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(); }); }); return app; }; 

mongoose.js

 var mongoose = require('mongoose'); module.exports = function() { var db = mongoose.connect("mongodb://localhost/stacktest"); require('./model'); return db; }; 

model.js

 var mongoose = require('mongoose'); var bcrypt = require("bcrypt-nodejs"); 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(); } }); userSchema.methods.authenticate = function (password) { var user = this; return bcrypt.compareSync(password,user.password); }; mongoose.model('Users', userSchema); 

passport.js

 var passport = require('passport'), LocalStrategy = require('passport-local'); module.exports = function() { passport.serializeUser(function (user, done) { done(null, user.id); }); passport.deserializeUser(function (id, done) { User.findById(id, function (err, user) { done(err, user); }); }); 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.')); } return done(null, user); }); } ) ); }; 

最后router.js

 var passport = require('./passport'); module.exports = function(app) { app.get('/', function (req, res) { res.redirect('/login'); //req.url = '/login'; //next(); }); app.get('/login', function (req, res) { res.render('login', {email: req.flash("email")[0], loginError: req.flash('loginError')}); }); app.post('/login', function (req, res, next) { passport.authenticate('local-login', function (err, user, info) { if (err) { return next(err); } if (!user) { return res.redirect('/login'); } return res.redirect('/?channel=' + req.body.email); })(req, res, next); }); app.get('/logout', function (req, res) { req.logout(); res.redirect('/login'); }); // set user routes 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] } ); }); // new }; 

我找不到“checkUserRegValidation”,所以我不得不删除(因为我认为它不是直接关系到有问题的错误),然后我做了两个ejs文件,用简单的标题标识页面(无论是login页面或索引),我得到了您的预期结果(当我的浏览器中放置localhost:// 3000时,login页面呈现)。 所以也许你可以尝试隔离你的文件,如果有帮助的话,抱歉的长答案。

你想在'/index.html'之前加载'/ login'我假设你希望用户在到达主页之前login。 此外,而不是redirect,尝试渲染。

在使用此代码之前,请将您的isLoggedIn重置为默认值。

  app.get('/', function(req, res) { if(!isLoggedIn) res.render('login') else res.redirect('/'); }); 
  • 请求包含无法识别的参数:在进行弹性search时请求获取build议
  • Node.jsexpression嵌套的路由
  • 节点js和expression式js的区别
  • 有没有办法创build一个由服务器处理产生的dynamic部分?
  • 将GETparameter passing给Express + Mongoose Restful API
  • Node.js Express mongoose查询查找
  • Express无法上传文件,req.files未定义
  • 在Express中响应数据到Slack url
  • Nodejs集群和expressjs会话
  • 如何在层之间传递http服务器variables,而不是将其作为node.js中不同文件中的require语句使用?
  • 给定一个图像的本地相对url,我怎样才能得到实际的图像发送