我在我的应用中使用Node,Express和Vuejs。我正在使用护照本地策略进行身份验证,并且工作正常。但是当我转到其他任何页面时,除了设置登录名后,req.user均未定义。
这是我的app.js
...
const MongoStore = require('connect-mongo')(session);
mongoose.connect(process.env.DATABASE);
const loginRouter = require('./routes/api/models/user/login');
const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors({ origin: process.env.CLIENT_HOST , credentials: true}));
app.use(cookieParser('secret'));
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(session({ store: new MongoStore({ mongooseConnection:
mongoose.connection, secret: 'secret' , resave: true, saveUninitialized: true,
cookie: {secure: true, _expires: 560000000}, httpOnly: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/api/models/user/login', loginRouter);
module.exports = app;
和passport.js文件
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({
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)
return done(null, false);
let newUser = new User();
newUser.email = email;
newUser.password = newUser.generateHash(password);
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
});
}));
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)
return done(null, false);
if (!user.verifyPassword(password))
return done(null, false);
return done(null, user);
});
...
login.js
router.post('/', passport.authenticate('local-login'),
function(req, res) {
res.send({ message: 'Login successful'})
}
);
user.js
const UserSchema = new Schema({
email: {
required: true,
type: String,
unique: true
},
password: {
required: true,
type: String
},
favoriteShops: [{ type: Schema.Types.ObjectId, ref: 'Shop' }]
});
UserSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
UserSchema.methods.verifyPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
const User = mongoose.model('User', UserSchema);
module.exports = User;
会话存储在数据库中。
我在这里和其他网站尝试了类似问题的许多解决方案,但均未成功。我可能缺少明显的东西。
如果有人可以指出我在做什么错,我将非常感激。