在登录逻辑中使用Passport JS添加错误/成功消息可以通过以下步骤实现:
npm install passport passport-local express-session connect-flash
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
const flash = require('connect-flash');
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) => {
// 在此处进行用户认证逻辑的实现
}));
app.post('/login', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}));
app.post('/login', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}), (req, res) => {
req.flash('success', '登录成功!');
res.redirect('/dashboard');
});
<% if (messages.error) { %>
<div class="alert alert-danger">
<%= messages.error %>
</div>
<% } %>
<% if (messages.success) { %>
<div class="alert alert-success">
<%= messages.success %>
</div>
<% } %>
通过以上步骤,您可以在Passport JS的登录逻辑中添加错误/成功消息。这样,当用户登录时,您可以根据身份验证的结果向用户显示相应的消息。
领取专属 10元无门槛券
手把手带您无忧上云