将用户应用于会话时,我似乎遇到了问题。当我登录时,该功能运行完美,bcrypt完美检查密码。但是当req.session.user = user
被调用时,我得到Cannot set property user of undefined
。
这是我的users.js文件
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var expressValidator = require('express-validator');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
router.use(expressValidator);
var UserModel = require('../models/user');
/* GET users listing. */
router.get('/register', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/login', function(req, res, next) {
res.send('respond with a resource');
});
router.registerUser = function(req,res){
console.warn('Getting Here');
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
console.log(req.body.name);
var newUser = new UserModel({
name:name,
email:email,
username:username,
password: password
});
UserModel.createUser(newUser, function(err,user){
if(err) throw err;
console.log(user);
});
}
router.login = function(req,res){
var username = req.body.username;
var password = req.body.password;
UserModel.findById("584340be3f63a303484eccc0", function(err, user){
console.warn(user.username);
console.warn(user.password);
bcrypt.compare(password , user.password, function(err,res) {
if (err) throw err;
});
console.warn (user);
req.session.user = user;
console.warn(req.session.user);
})
}
module.exports = router;
正如您在文件中看到的那样,我在数据库中查找用户并比较其字符串。如果字符串是正确的,我只想将用户添加到会话中。这是我的app.js文件,其中包含中间件。
var session = require('express-session');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var passport = require('passport');
var LocalStrategy = require('passport-local'),Strategy;
var mongo = require('mongoose');
var routes = require('./routes/index');
var users = require('./routes/users');
var candidates = require('./routes/candidates.js');
var supporters = require('./routes/supporters.js');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.get('/candidates', candidates.findAll);
app.get('/candidates/:id', candidates.findOne);
app.put('/candidates/:id/votes', candidates.incrementUpvotes);
app.delete('/candidates/:id', candidates.deleteCandidate);
app.get('/supporters', supporters.findAll);
app.get('/supporters/:id', supporters.findOne);
app.post('/supporters',supporters.addPerson);
app.post('/candidates', candidates.addPerson);
app.post('/candidates/:id',candidates.updateCandidate);
app.post('/image',candidates.addImage);
app.post('/register', users.registerUser);
app.post('/login', users.login);
app.delete('/supporters/:id', supporters.deleteSupporter);
// catch 404 and forward to error handler
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
cookieName: 'session',
secret: 'random_string_goes_here',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param,msg,value){
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return{
param: formParam,
msg: msg,
value: value
};
}
}
));
//Connect Flash
app.use(flash());
app.use(function(req,res,next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
我已经在这个问题上待了很长一段时间了,并且想知道是否有人能把我送到正确的方向。提前谢谢!
答案 0 :(得分:0)
我发现了这个问题。在app.js中,我将一些app.use函数放在app.user('router')下面,这导致了问题