我正在读一本关于node.js、express 和 mongodb 的书。作者使用connect-flash。但是,我似乎无法让它正常工作。下面是使用connect-flash的文件夹,去掉了不相关的代码。
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('/')
})
}
Controller /newUser.js:
module.exports = (req, res) =>{
res.render('register',{
errors: flash('validationErrors')
})
}
错误
引用错误:闪存未定义。
此错误发生在controllers\newUser.js:3:17)
我已经多次重读这一章并寻找解决方案,但没有运气。我不明白为什么它在index.js中声明时是未定义的。
为什么 flash 未定义?我该如何解决这个问题?
最佳答案
module.exports = (req, res) =>{
res.render('register',{
errors: req.flash('validationErrors')
})
}
您可能错过了从 req 调用它。
关于javascript - 连接闪存错误消息 : flash is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62629825/