0

我有一个使用 passportjs 的项目可以正常工作,但没有显示 Flash 消息。

passportjs 文件如下所示:

  passport.use('local-login', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
  },
  function (req, email, password, done) {
    if (email) {
      email = email.toLowerCase()
    } // Use lower-case e-mails to avoid case-sensitive e-mail matching

    // asynchronous
    process.nextTick(function () {
      User.findOne({ 'local.email': email }, function (err, user) {
        // if there are any errors, return the error
        if (err) {
          console.log(err)
          return done(err)
        }

        // if no user is found, return the message
        if (!user) {
          console.log('No user found')
          return done(null, false, req.flash('message', 'No user found'))
        }

我的 routes.js 文件如下所示:

  // Login
  app.get('/login', function (req, res) {
    console.log('login get')
    res.render('pages/login', {message: req.flash('messsage')})
  })

我的 login.ejs 文件如下所示:

  <%if (message) {%>
    <%=message%>

  <%}%>

我不知道为什么它不起作用?

如果有任何与包含相关的问题,我的 server.js 会出现:

var express = require('express')
var mongoose = require('mongoose')
var passport = require('passport')
var path = require('path')
var ejs = require('ejs') // Not used?
var fs = require('fs') // Not used?

const session = require('express-session')
const MongoStore = require('connect-mongo')(session)

// Reads .env variables for encrypted data
require('dotenv').config()

var port = process.env.PORT || 8080
var db = process.env.MONGO_URI

mongoose.connect(db) // connect to our database

var app = express()

app.set('views', './views')
app.set('view engine', 'ejs')

// GET /public/style.css etc.
app.use(express.static(path.join(__dirname, '/public')))

var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded())

app.use(session({
  secret: 'hakunamatata',
  store: new MongoStore({
    mongooseConnection: mongoose.connection,
    saveUninitialized: false,
    resave: false
  })
}))

var flash = require('connect-flash')
app.use(flash())

var initPassport = require('./app/authentication/passport')
initPassport(passport)

app.use(passport.initialize())
app.use(passport.session()) // persistent login sessions

require('./app/routes/routes')(app, passport)

app.listen(port)
console.log('Dev port is: ' + port)
4

1 回答 1

0

我测试过:

req.flash('loginMessage', 'No user found')

代替:

req.flash('message', 'No user found')

在 routes.js 文件中:

{message: req.flash('loginMessage')}

代替:

{message: req.flash('message')}

现在它起作用了......我不知道有什么不同,但我希望这可以在未来帮助其他人..

于 2017-04-21T08:40:57.920 回答