我有一个中间件isAuthenticated
,以确保用户在发布评论之前已登录:
function isAuthenticated(req,res,next) {
req.isAuthenticated ? next() : res.redirect('/login');
}
这个中间件假设在这里运行:
router.post('/cat/:id', isAuthenticated, function(req,res) {
console.log('not suppose to be here');
var id = req.params.id;
Cat.findById(id, function(err, cat) {
if (err) {
console.log(err);
} else {
var id = req.params.id;
var comment = new Comment({
username: req.user.username,
content: req.body.content
});
//more code
但是,当我尝试在不登录的情况下发布评论时,我的应用程序崩溃,控制台显示以下内容:
not suppose to be here
username: req.user.username,
^
TypeError: Cannot read property 'username' of undefined
我将所有路由重构为一个单独的文件,并将其导出到app.js.与猫有关的所有路线都存储在cats.js
:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var Cat = require('../models/cat.js');
var Comment = require('../models/comment.js');
var mongoose = require('mongoose');
router.use(function(req,res,next) {
res.locals.user = req.user;
next();
});
function isAuthenticated(req,res,next) {
req.isAuthenticated ? next() : res.redirect('/login');
}
router.get('/cat/:id', function(req,res) {
var id = req.params.id;
Cat.findById(id, function(err, cat) {
if (err) {
console.log(err);
} else {
Comment.find({}, function(err, comments) {
if (err) {
console.log(err);
} else {
res.render('show', {cat:cat, comments:comments});
}
});
}
});
});
//more code
module.exports = router;
app.js :
var app = express();
var bodyParser = require('body-parser');
var config = require('./config/config.js');
var mongoose = require('mongoose');
var Cat = require('./models/cat.js');
var Comment = require('./models/comment.js');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var passportLocalMongoose = require('passport-local-mongoose');
var User = require('./models/user.js');
mongoose.connect(config.dbURL, function(err) {
if (err) {
console.log(err);
} else {
console.log('successfully connected to database!');
}
});
app.set('view engine', 'ejs');
app.use(session({
secret:"sfsdfsdfsd",
resave: false,
saveUninitialized: false
}));
app.use(bodyParser.urlencoded({extended:true}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.engine('html', require('ejs').renderFile);
app.use(express.static('public'));
var authRoutes = require('./routes/auth.js');
var catRoutes = require('./routes/cats.js');
app.use(authRoutes);
app.use(catRoutes);
为什么绕过我的中间件?如果需要,请询问其他代码。
Edit1 :已更新以提供更多信息。
答案 0 :(得分:0)
我解决了这个问题。我忘了在我的中间件中调用req.isAuthenticated
。我有它:
function isAuthenticated(req,res,next) {
req.isAuthenticated ? next() : res.redirect('/login');
}
它应该是req.isAuthenticated()
。