我有一个问题,当用户注销时,使用Express框架将Flash消息传递到pug视图。我认为这是由于以下事实引起的:当用户单击注销链接(在导航栏中)时,我正在销毁会话,然后将用户重定向到首页(“ index ”哈巴狗视图)当出现消息“ 您现在已退出”时。对于Flash消息,我使用的是基于connect-flash的Express-Flash软件包,该软件包需要会话以传递Flash消息。
我成功传递消息的唯一方法不是在response.redirect(301, '/')
路由器中使用response.render('index', {msg: 'You are now logged out')
,而是使用app.get('/logout')
。但是,要使此工作有效,我需要注释掉Flash中间件的使用。否则,我会遇到“ 闪光灯需要会话”错误。阻碍了我同时使用Flash中间件和这种方法。
一旦销毁了会话并在未销毁会话的情况下使用Flash中间件,有什么办法可以传递此消息?还是我不应该在用户注销时销毁会话?也许还有其他方法不采用会话机制来传递此类消息(例如,将用户重定向到用于显示消息的单独视图)?
我正在发布相关代码:
这是 app.js:
'use strict';
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const routes = require('./routes/index');
const config = require('./config');
const session = require('express-session');
const flash = require('express-flash');
const MongoStore = require('connect-mongo')(session);
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser(config.secretKey));
app.use(session({
store: new MongoStore({
mongooseConnection: mongoose.connection,
}),
name: 'ga_id',
secret: config.secretKey,
resave: false,
saveUninitialized: true,
}));
//app.use(flash());
app.use('/', routes);
这是 index.js:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { check, validationResult } = require('express-validator/check');
const { sanitize, matchedData } = require('express-validator/filter');
const crypto = require('crypto');
require('../models/users');
const Users = mongoose.model('Users');
/* #### Router for Homepage #### */
router.get('/', function(request, response){
let name = request.session.name;
//let messages = request.flash('logout');
//console.log(messages);
response.render('index', {
pageTitle: "EasyTemplate",
user: name,
//flashMsg: messages
});
});
--snip--
router.get('/logout', function(request, response) {
//request.flash('logout', 'You are now logged out!');
request.session.destroy(function(error) {
//response.redirect(301, '/');
response.render('index', {
msg: 'You are now logged out!'
});
});
});
--snip--
router.post('/login',
[
check('email')
.not().isEmpty().withMessage('The field email is required').trim().escape()
.isEmail().withMessage('Please introduce a valid email address'),
check('pass')
.not().isEmpty().withMessage('The field password is required').trim().escape()
],
function(request, response, next) {
const errors = validationResult(request);
let err = errors.mapped();
if (errors.isEmpty()) {
Users.findOne({email: request.body.email}, function(err, user) {
console.log(user);
return user;
}).then(function(user) {
if (user.email === request.body.email && user.checkPassword(request.body.pass)) {
request.session.regenerate(function(err) {
request.session.name = user.firstName + ' ' + user.lastName;
response.redirect('/account');
});
} else {
response.render('login', {
failed: 'The email or the password do not match!'
});
}
}).catch(function(error) {
response.render('login', {
failed: 'Something went wrong with your login!'
})
});
} else {
response.render('login', {
pageTitle: 'Login',
errors: err,
});
}
});
module.exports = router;
这是 index.pug:
extends layout
block content
if msg
.alert.alert-success=msg
.card.w-75.main-title
img.card-img-top(src="/images/blue-bg.jpg" height="10")
.card-body.text-center
h2.main-title-header Welcome to Easy Template!
p.lead.font-italic Creating modular legal documents
.card.w-75.contracts
img.card-img-top(src="/images/blue-bg.jpg" height="10")
.card-body.text-center
h3.section-header.shadow
a(href="/contracts") Contracts
p.lead.font-italic Build modular contracts on the fly
.card.w-75.corporate-docs
img.card-img-top(src="/images/blue-bg.jpg" height="10")
.card-body.text-center
h3.section-header.shadow
a(href="/corporate") Corporate Documents
p.lead.font-italic Instant customized corporate documents
.card.w-75.notice
img.card-img-top(src="/images/blue-bg.jpg" height="10")
.card-body.text-center
h3.section-header.shadow
a(href="/notices") Notices
p.lead.font-italic Notices are never being so easy
这是 start.js
const app = require('./app');
const config = require('./config');
require('./db');
let port = config.port|| 3000;
const server = app.listen(port);
console.log("The server is running on port: " + port);
这是 layout.pug
- var error = err || ''
doctype html
html(lang="en")
head
title=pageTitle
meta(name='viewport', content='width=device-width, initial-scale=1.0')
link(rel="stylesheet" href="bootstrap/dist/css/bootstrap.css")
link(rel="stylesheet" href="css/reset.css")
link(rel="stylesheet" href="css/base.css")
link(href="https://fonts.googleapis.com/css?family=Artifika" rel="stylesheet")
body
nav.navbar.navbar-expand-lg
a.navbar-brand(href="#") Easy Template
.collapse.navbar-collapse
ul.navbar-nav
li.nav-item
a.nav-link(href="/") Home
li.nav-item
a.nav-link(href="/contracts") Contracte
li.nav-item
a.nav-link(href="/corporate") Documente Societare
li.nav-item
a.nav-link(href="/notices") Notificări
li.nav-item
a.nav-link Contact
li.nav-item
a.nav-link(href="/about") Despre Noi
li.nav-item
a.nav-link(href="/register") Inregistrare
if user
li.nav-item
a.nav-link(href="/logout")
span='Log-out '
i(data-feather="log-out")
li.nav-item
a.nav-link(href="/account")
span='Account '
i(data-feather="user")
else
li.nav-item
a.nav-link(href="/login")
span='Login '
i(data-feather="log-in")
main.container-fluid
block content
.footer
script(src='jquery/dist/jquery.min.js')
script(src='popper.js/dist/popper.js')
script(src='bootstrap/dist/js/bootstrap.js')
script(src='https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js')
script feather.replace({ width: 16, height: 16});
最后是 package.json:
{
"name": "easytemplate",
"description": "First Template App",
"version": "0.0.1",
"private": true,
"dependencies": {
"body-parser": "^1.18.3",
"bootstrap": "^4.1.1",
"connect-mongo": "^2.0.1",
"cookie-parser": "^1.4.3",
"dotenv": "^5.0.0",
"express": "latest",
"express-flash": "0.0.2",
"express-session": "^1.15.6",
"express-validator": "^5.2.0",
"jquery": "^3.3.1",
"lodash": "^4.17.10",
"mongoose": "^5.1.5",
"popper.js": "^1.14.3",
"pug": "^2.0.0-rc.4"
},
"scripts": {
"start": "node start.js",
"watch": "nodemon ./start.js"
},
"devDependencies": {
"nodemon": "^1.17.5"
}
}