我读过类似的问题,但我找不到解决方法。
在我的server.js
文件中:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var passport = require('passport');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var passportHelp = require('./config/passport');
var flash = require('connect-flash');
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('view engine', '.hbs');
app.set('views', path.join(__dirname, './app/views'))
app.use(expressSession({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
passportHelp(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(require('./app/controllers'));
app.listen(3000);
在./app/controllers
中var express = require('express');
var router = express.Router();
router.use(require('./signup'));
module.exports = router;
在./controllers/signup
中var express = require('express');
var passport = require('passport');
var router = express.Router();
router.get('/signup', function(req, res) {
res.render('signup');
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true,
}));
module.exports = router;
最后,在./config/passport
中 var LocalStrategy = require('passport-local').Strategy;
var User = require('../app/models/user');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
console.log(req.body.username);
console.log(req.body.password); //successfully logs all of these 3
console.log(req.body.email);
process.nextTick(function() {
User.findOne({ 'username' : username }, function(err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
}
else {
var newUser = new User;
//filling new user data here
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
我最终表现得很奇怪。有时POST
没有问题,有时我得cannot POST /signup
,但结果仍保存到数据库中。
我已经尝试在server.js
文件中切换一些行,但没有结果。正如我读过的那样,require passport
中的controller/signup
时,它应该是server.js
中我'初始化'的“护照”对象,所以我最终不会以新鲜的方式工作passport
对象。我是对的吗?
答案 0 :(得分:0)
如果有人面临同样的问题。
我收到错误的原因,但保存到数据库中是成功的,我已评论该行:SessionFactory