Search code examples
javascriptnode.jsexpressconnect-flash

Error message with connect-flash: flash is not defined


I'm reading a books about node.js, express and mongodb. The author uses connect-flash. However, I can't seem to get it to work correctly. The folders in which connect-flash is used is shown below with the irrelevant code removed.

index.js

const flash = require('connect-flash');
app.use(flash());

const newUserController = require('./controllers/newUser')
const storeUserController = require('./controllers/storeUser') 

app.get('/auth/register', redirectIfAuthenticatedMiddleware, newUserController)
app.post('/users/register', redirectIfAuthenticatedMiddleware, storeUserController)

controllers/storeUser.js

const User = require('../models/User.js')
const path = require('path')

module.exports = (req,res)=>{
    User.create(req.body, (error, user) => {
        if(error){
            const validationErrors = Object.keys(error.errors).map(key => error.errors[key].message)
            // req.session.validationErrors = validationErrors
            req.flash('validationErrors',validationErrors)
            return res.redirect('/auth/register');
        }
        res.redirect('/')
    })
}

Controllers/newUser.js:

module.exports = (req, res) =>{
    res.render('register',{
        errors: flash('validationErrors')
    })
}

The error

ReferenceError: flash is not defined.

This error occurs at controllers\newUser.js:3:17)

I have reread the chapter many times and searched for a solution without luck. I don't understand why it's undefined when it's declared in index.js.

Why is flash undefined? and how do I fix it?


Solution

  • module.exports = (req, res) =>{
        res.render('register',{
            errors: req.flash('validationErrors')
        })
    }
    

    You may be missing calling it from req.