我有一个关于在DB中持久化会话的问题。
我尝试将会话存储在MemoryStore中以跟踪会话的内容,结果如预期,其他一切都按预期工作。
但是对于MongoStore,会话集合在DB中得到createad,其他一切都按预期工作,但是会话没有存储在DB中!!
下面是代码:(我使用 Postman 发送请求)
索引. js--〉
const express = require('express');
require('./db');
const passport = require('passport');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const MongoStore = require('connect-mongo');
const authRouter = require('./routes/auth');
const productsRouter = require('./routes/routing');
require('./routes/passport-local');
// const memoryStore = new session.MemoryStore();
const app = express();
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on Port ${PORT}`));
app.use(express.json());
app.use(cookieParser());
app.use(
session({
secret: 'ALKSDFLKSDLFMK',
resave: false,
saveUninitialized: false,
sotre: MongoStore.create({
mongoUrl: 'mongodb://localhost/express_tuto',
}),
// store: memoryStore,
})
);
app.use(passport.initialize());
app.use(passport.session());
// app.use((req, res, next) => {
// console.log(memoryStore);
// console.log(req.user);
// next();
// });
app.use('/auth', authRouter);
app.use('/products', productsRouter);
./路径/身份验证. js--〉
const { Router } = require('express');
const passport = require('passport');
const router = Router();
router.post(
'/login',
passport.authenticate('local'),
(req, res) => {
console.log(req.session);
console.log(req.user);
console.log(`sessionID: ${req.sessionID}`);
res.send('Logged in');
}
);
module.exports = router;
./路线/护照-本地. js--〉
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const User = require('../db/schemas/User');
const passport = require('passport');
passport.serializeUser((user, done) => {
console.log('serializing');
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
console.log('deserializing');
try {
const user = await User.findById(id);
if (user) {
done(null, user);
}
} catch (err) {
console.log(err);
done(err, null);
}
});
passport.use(
new LocalStrategy(
{ usernameField: 'email' },
async (email, password, done) => {
const user = await User.findOne({ email });
if (!user) {
console.log('no matching email!');
done(null, false);
}
try {
if (await bcrypt.compare(password, user.password)) {
console.log('user found');
done(null, user);
} else {
console.log('password incorrect');
done(null, false);
}
} catch (err) {
return done(err);
}
}
)
);
我希望看到会话存储在DB中,因为其他一切都按预期工作!
1条答案
按热度按时间8xiog9wr1#
我的错,会话存储选项中有一个错字。