刷新页面后的nodejs会话

时间:2017-04-06 19:08:08

标签: node.js ejs

这是一个简单的登录表单。我已经验证了一封电子邮件,如果电子邮件无效则会出错(这里没问题)。刷新该页面而不是显示登录表单后,它还会在该页面上显示错误以及登录表单。

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var hbs = require('express-handlebars');
var expressValidator = require('express-validator');
var expressSession = require('express-session');

var routes = require('./routes/index');

var app = express();

// view engine setup
//app.engine('hbs', hbs({extname: 'ejs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({secret: 'max', saveUninitialized: false, resave: false}));

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

index.js文件

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  console.log(req.session);
  res.render('student_login', { success: req.session.success, errors: req.session.errors });
  req.session.errors = null;
  console.log(req.session);
});

router.get('/submit', function(req, res, next) { 
  req.check('e', 'Invalid email address').isEmail();
  //req.check('p', 'Password is invalid').isLength({min: 4}).equals(req.body.confirmPassword);

  var errors = req.validationErrors();
  if (errors) {
    console.log(req.session);
    req.session.errors = errors;
    req.session.success = false;
    console.log(req.session);
  } else {
    console.log(req.session);
    req.session.success = true;
    console.log(req.session);
  }
  res.redirect('/');
});

module.exports = router;

student_login.ejs

    <!DOCTYPE html>
<html >

    <% if(success ){ %>
        <h1>validation succesful</h1>
    <% } 
    else{ %>
        <ul>
        <% if(errors) {%>
           <h1> errors </h1>
        <% } %>
        </ul>
    <h1>Login</h1>
    <form action="/submit" method="get"> 
        <input type="text" name="e" placeholder="Email" required="required" > <br>
        <input type="password" name="p" placeholder="Password" required="required" > <br>
        <button type="submit" >Let me in.</button>
    </form>

<% } %>
</html>

1 个答案:

答案 0 :(得分:1)

此处的问题是您在会话中保存错误,这意味着它将保留在会话中,除非您清除它或会话结束。

您需要的是 Flash消息。这些是存储在会话中的类似消息,但是一旦向用户显示它们就被清除,因此它们只显示一次。

之前我使用过connect-flash节点模块。它很容易设置并完美地完成工作。