我正在尝试使用 EJS 和 connect-flash 以及 express 和 express-session 将我的大脑包裹在模板和 flash 消息上,但我似乎无法让它以我想要或预期的方式工作。
当我定义一个 flash 消息时,我 console.log 它,我可以很好地看到它。但是当我尝试在我的模板中打印它时,它req.flash
是一个空对象 [object Object]。
登录尝试失败后,console.log 中的闪烁消息:
flash(): { error: [ 'Brugernavn eller adgangskode er ikke korrekt.' ] }
但是当我尝试flash
在我的 ejs 模板中循环使用类似的东西时
<% flash.forEach(function (message) { %>
<p><%=message%></p>
<% }) %>
以上返回错误
TypeError: C:\path\to\my\stuff\auth-test\views\login.ejs:7
[snippet with line indicator, not important]
flash.forEach is not a function
服务器.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)
前端路由器.js
(注意 .post 和 .get '/login' 的路由)
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('/')
})
}
登录.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(): {}