EJS 和 connect-flash 没有按预期工作
EJS and connect-flash doesn't work as expected
我正在尝试使用 EJS 和 connect-flash 以及 express 和 express-session 将我的大脑围绕在模板和 flash 消息上,但我似乎无法让它按照我想要或期望的方式工作。
当我定义一个 flash 消息时,我 console.log 它,我可以很好地看到它。但是当我尝试在我的模板中打印它时,req.flash
是一个空对象 [object Object].
登录尝试失败后 console.log 中的闪现消息:
flash(): { error: [ 'Brugernavn eller adgangskode er ikke korrekt.' ] }
但是当我尝试在我的 ejs 模板中使用
之类的东西循环遍历 flash
时
<% flash.forEach(function (message) { %>
<p><%=message%></p>
<% }) %>
以上returns错误
TypeError: C:\path\to\my\stuff\auth-test\views\login.ejs:7
[snippet with line indicator, not important]
flash.forEach is not a function
server.js
const myExpress = require('express')
const myApp = myExpress()
const myBodyParser = require('body-parser')
const flash = require('connect-flash')
const mySession = require('express-session')
const myLogger = require('morgan')
const myFs = require('fs')
const myPath = require('path')
const myEjs = require('ejs')
const myLRU = require('lru-cache')
const myAccessLogStream = myFs.createWriteStream(myPath.join(__dirname, 'logs', 'access.log'), { flags: 'a' })
const myPort = process.env.PORT || 1337
const myAuthCheck = function (myRequest) {
if (!myRequest.session || !myRequest.session.authenticated) {
return false
}
else {
return true
}
}
myApp.engine('ejs', require('express-ejs-extend'))
myApp.set('view engine', 'ejs')
myEjs.cache = myLRU(100)
myApp.use(flash())
myApp.use(mySession({ secret: 'meget hemmelig streng', resave: true, saveUninitialized: true }))
myApp.use(myBodyParser.urlencoded({'extended': 'true', limit: '50mb'}))
myApp.use(myBodyParser.json())
myApp.use(myBodyParser.json({ type: 'application/vnd.api+json', limit: '50mb' }))
myApp.use(myLogger('combined', { stream: myAccessLogStream }))
var hourMs = 1000 * 60 * 60
myApp.use(myExpress.static(__dirname + '/public', { maxAge: hourMs }))
require('./routers/frontendRouter')(myApp, myAuthCheck)
myApp.listen(myPort)
console.log('Serveren kører på http://localhost:' + myPort)
frontendRouter.js
(注意'/login'的.post和.get路由)
const fetch = require('node-fetch')
module.exports = function (myApp, myAuthCheck) {
myApp.get('/', function (myRequest, myResponse) {
myResponse.render('home', { title: 'Hello, World!', data: 'Something wicked this way comes!' })
})
myApp.get('/test', function (myRequest, myResponse) {
myResponse.render('article', { title: 'Dette er en test', data: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor veniam voluptatibus vel omnis nostrum maiores, placeat! Nam ea asperiores, sint, aut reprehenderit eos, facere ipsum in, ratione sunt ab fugiat?'})
})
myApp.get('/profile', function (myRequest, myResponse) {
if (!myAuthCheck(myRequest)) {
myResponse.render('403', { title: 'Adgang forbudt', status: 403 })
}
else {
myResponse.render('profile', { title: 'Profil' })
}
})
myApp.post('/login', function (myRequest, myResponse) {
if (myRequest.body.username && myRequest.body.username === 'admin' && myRequest.body.password && myRequest.body.password === '1234') {
myRequest.session.authenticated = true
myResponse.redirect('/profile')
}
else {
myRequest.flash('error', 'Brugernavn eller adgangskode er ikke korrekt.')
console.log('flash():', myRequest.flash())
myResponse.redirect('/login')
}
})
myApp.get('/login', function (myRequest, myResponse) {
myResponse.render('login', { title: 'Log ind', flash: myRequest.flash() })
})
myApp.get('/logout', function (myRequest, myResponse) {
delete myRequest.session.authenticated
myResponse.redirect('/')
})
}
login.ejs
<% extend('layout') %>
<section>
<h1><%=title%></h1>
<form action="" method="post">
<p><input type="text" name="username" placeholder="Brugernavn"></p>
<p><input type="password" name="password" placeholder="Adgangskode"></p>
<% flash.forEach(function (message) { %>
<p><%=message%></p>
<% }) %>
<button type="submit">Log ind</button>
</form>
</section>
编辑:
我现在在发送端和接收端都console.log()'ed req.flash():
myApp.get('/login', function (myRequest, myResponse) {
console.log('flash():', myRequest.flash())
myResponse.render('login', { title: 'Log ind', flash: myRequest.flash() })
})
而接收端的结果是
flash(): {}
从flash()
返回的值是一个对象:
{ error: [ 'Brugernavn eller adgangskode er ikke korrekt.' ] }
因此,要处理和显示错误,您将使用如下内容:
<% (flash.error || []).forEach(function(message) { %>
<p><%=message%></p>
<% }) %>
或者更明确一点(通过仅将错误提示消息传递给模板):
// code
res.render('template', { errors : req.flash('error') || [] });
// template
<% errors.forEach(function(message) { %>
<p><%=message%></p>
<% }) %>
要解决 GET /login
中对象为空的问题,请确保在设置和获取对象之间的任何地方都不要调用 req.flash()
(例如,通过 console.log
'正在处理它)。一旦你调用 req.flash()
,所有存储的消息都将被删除(非常没有记录,但这就是 req.flash()
在 Express 2.x 中的行为方式,connect-flash
试图模仿)。
我正在尝试使用 EJS 和 connect-flash 以及 express 和 express-session 将我的大脑围绕在模板和 flash 消息上,但我似乎无法让它按照我想要或期望的方式工作。
当我定义一个 flash 消息时,我 console.log 它,我可以很好地看到它。但是当我尝试在我的模板中打印它时,req.flash
是一个空对象 [object Object].
登录尝试失败后 console.log 中的闪现消息:
flash(): { error: [ 'Brugernavn eller adgangskode er ikke korrekt.' ] }
但是当我尝试在我的 ejs 模板中使用
之类的东西循环遍历flash
时
<% flash.forEach(function (message) { %>
<p><%=message%></p>
<% }) %>
以上returns错误
TypeError: C:\path\to\my\stuff\auth-test\views\login.ejs:7
[snippet with line indicator, not important]
flash.forEach is not a function
server.js
const myExpress = require('express')
const myApp = myExpress()
const myBodyParser = require('body-parser')
const flash = require('connect-flash')
const mySession = require('express-session')
const myLogger = require('morgan')
const myFs = require('fs')
const myPath = require('path')
const myEjs = require('ejs')
const myLRU = require('lru-cache')
const myAccessLogStream = myFs.createWriteStream(myPath.join(__dirname, 'logs', 'access.log'), { flags: 'a' })
const myPort = process.env.PORT || 1337
const myAuthCheck = function (myRequest) {
if (!myRequest.session || !myRequest.session.authenticated) {
return false
}
else {
return true
}
}
myApp.engine('ejs', require('express-ejs-extend'))
myApp.set('view engine', 'ejs')
myEjs.cache = myLRU(100)
myApp.use(flash())
myApp.use(mySession({ secret: 'meget hemmelig streng', resave: true, saveUninitialized: true }))
myApp.use(myBodyParser.urlencoded({'extended': 'true', limit: '50mb'}))
myApp.use(myBodyParser.json())
myApp.use(myBodyParser.json({ type: 'application/vnd.api+json', limit: '50mb' }))
myApp.use(myLogger('combined', { stream: myAccessLogStream }))
var hourMs = 1000 * 60 * 60
myApp.use(myExpress.static(__dirname + '/public', { maxAge: hourMs }))
require('./routers/frontendRouter')(myApp, myAuthCheck)
myApp.listen(myPort)
console.log('Serveren kører på http://localhost:' + myPort)
frontendRouter.js
(注意'/login'的.post和.get路由)
const fetch = require('node-fetch')
module.exports = function (myApp, myAuthCheck) {
myApp.get('/', function (myRequest, myResponse) {
myResponse.render('home', { title: 'Hello, World!', data: 'Something wicked this way comes!' })
})
myApp.get('/test', function (myRequest, myResponse) {
myResponse.render('article', { title: 'Dette er en test', data: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor veniam voluptatibus vel omnis nostrum maiores, placeat! Nam ea asperiores, sint, aut reprehenderit eos, facere ipsum in, ratione sunt ab fugiat?'})
})
myApp.get('/profile', function (myRequest, myResponse) {
if (!myAuthCheck(myRequest)) {
myResponse.render('403', { title: 'Adgang forbudt', status: 403 })
}
else {
myResponse.render('profile', { title: 'Profil' })
}
})
myApp.post('/login', function (myRequest, myResponse) {
if (myRequest.body.username && myRequest.body.username === 'admin' && myRequest.body.password && myRequest.body.password === '1234') {
myRequest.session.authenticated = true
myResponse.redirect('/profile')
}
else {
myRequest.flash('error', 'Brugernavn eller adgangskode er ikke korrekt.')
console.log('flash():', myRequest.flash())
myResponse.redirect('/login')
}
})
myApp.get('/login', function (myRequest, myResponse) {
myResponse.render('login', { title: 'Log ind', flash: myRequest.flash() })
})
myApp.get('/logout', function (myRequest, myResponse) {
delete myRequest.session.authenticated
myResponse.redirect('/')
})
}
login.ejs
<% extend('layout') %>
<section>
<h1><%=title%></h1>
<form action="" method="post">
<p><input type="text" name="username" placeholder="Brugernavn"></p>
<p><input type="password" name="password" placeholder="Adgangskode"></p>
<% flash.forEach(function (message) { %>
<p><%=message%></p>
<% }) %>
<button type="submit">Log ind</button>
</form>
</section>
编辑:
我现在在发送端和接收端都console.log()'ed req.flash():
myApp.get('/login', function (myRequest, myResponse) {
console.log('flash():', myRequest.flash())
myResponse.render('login', { title: 'Log ind', flash: myRequest.flash() })
})
而接收端的结果是
flash(): {}
从flash()
返回的值是一个对象:
{ error: [ 'Brugernavn eller adgangskode er ikke korrekt.' ] }
因此,要处理和显示错误,您将使用如下内容:
<% (flash.error || []).forEach(function(message) { %>
<p><%=message%></p>
<% }) %>
或者更明确一点(通过仅将错误提示消息传递给模板):
// code
res.render('template', { errors : req.flash('error') || [] });
// template
<% errors.forEach(function(message) { %>
<p><%=message%></p>
<% }) %>
要解决 GET /login
中对象为空的问题,请确保在设置和获取对象之间的任何地方都不要调用 req.flash()
(例如,通过 console.log
'正在处理它)。一旦你调用 req.flash()
,所有存储的消息都将被删除(非常没有记录,但这就是 req.flash()
在 Express 2.x 中的行为方式,connect-flash
试图模仿)。