获取 connect-flash 包以呈现 flash 消息

Getting connect-flash package to render flash message

我正在通过练习学习 expressjs 和 mongodb。 我想在添加、更新或删除新项目时呈现 flash 消息。尽管我也没有收到任何错误,但它不起作用,因此很难查明确切原因。下面是我的主要代码:

const express = require('express');
const exphbs = require('express-handlebars');
const methodOverride = require('method-override'); //dynamically overrides     post when it's time to PUT (update)
const flash = require('connect-flash');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();

//Load routes
const ideas = require('./routes/ideas');
const users = require('./routes/users');

//connect to mongoose
mongoose.connect('mongodb://localhost/vidjot-dev')
.then(()=>console.log('MongoDB Conneced....'))
.catch(err => console.log(err));

//handlebars Middleware
app.engine('handlebars', exphbs({
defaultLayout: 'main'
}));

app.set('view engine', 'handlebars');

//Body parser middleware - allows us to access whatever is submitted from     the form of the request object
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//method Override middleware
app.use(methodOverride('_method'));




app.use(cookieParser('secret'));
app.use(session({cookie: { maxAge: 60000 }}));
app.use(flash());


//Index Route
app.get('/', (req, res)=>{
const myTitle="Welcome Isaac S.";
res.render('INDEX', {
    title:myTitle
});
});

//About Route
app.get('/about', (req, res)=>{
res.render('ABOUT');
})

//use routes
app.use('/ideas', ideas);
app.use('/users', users);

//Use nodemon app to connect
const port = 5500;
app.listen(port, ()=> {
console.log(`Server started on port ${port}`);

/*Same as above which is ES6 */
//console.log('Server started on port '+port);
})

'routes.js'代码

const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();

//Load Idea Model
require('../models/Idea');
const Idea = mongoose.model('ideas')

//Idea Index Page
router.get('/', (req, res) => {
Idea.find({}) //<== Returns all data
    .sort({date:'desc'})
    .then(ideas => {
        res.render('ideas/index', {                
            ideas:ideas
        });
    })
});

//Add Idea Form
router.get('/add', (req, res)=>{
res.render('ideas/add');
})

//Edit Idea Form
router.get('/edit/:id', (req, res)=>{
Idea.findOne({
    _id: req.params.id //passed in from the url   
})
.then(idea => { //<== returns single data queried for with above :id
    res.render('ideas/edit', {
    idea:idea
    });
  });
});

//Process Form
router.post('/', (req, res)=>{
let errors = [];

if(!req.body.title){
    errors.push({text:'Please add a title'});
}
if(!req.body.details){
    errors.push({text:'Please add somee details'});
}    

if(errors.length > 0){
    res.render('ideas/add', {
        errors: errors,
        title: req.body.title,
        details: req.body.details
    });
}else {
    const newUser = {
        title: req.body.title,
        details: req.body.details
    }
    new Idea(newUser)
        .save()
        .then(idea=> {
            req.flash('success_msg', 'Video idea added');
            res.redirect('/ideas');
        })
}
})

//Edit Form Process
router.put('/:id', (req, res) =>{
Idea.findOne({
    _id:req.params.id
})
.then(idea => {
    //new values
    idea.title = req.body.title;
    idea.details = req.body.details;

    idea.save()
        .then(idea => {
            req.flash('success_msg', 'Video idea updated');
            res.redirect('/ideas');
        })
});
});

//Delete Idea
router.delete('/:id', (req, res)=>{
Idea.remove({_id: req.params.id})
    .then(()=>{
        req.flash('success_msg', 'Video idea removed');
        res.redirect('/ideas');
    });
});

module.exports = router;

这是我的仓库 https://github.com/isogunro/express-exercise

看来你从来没有用过flash值。您需要将 flash 消息传递给模板:

app.use(function(req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
})