【问题标题】:Trouble understanding how exactly to use connect-flash with Express 4.x?难以理解如何在 Express 4.x 中使用 connect-flash?
【发布时间】:2023-03-17 21:52:01
【问题描述】:

所以基本情况是,我有一个登录表单 - 如果用户输入了错误的帐户信息,我希望它重定向回登录页面并显示一条消息,说明他们输入了错误的信息 - 对现在我只是试图在测试消息中输出,以确保我对此有一个有效的理解。

对于理解 connect-flash 的基本指南(因为这似乎是我完成这项工作所需的工具),我已经从高到低看了一遍,但我并不完全理解它 - 我已经编写了一些代码尝试实现它,但在编译我的 Jade 文件时我不断收到此错误:

TypeError: index.jade:28
    26|       form.form-signin(method="post", action="/loginSuccess")
    27|         h2.form-signin-heading(style="text-align:center;") Please sign in
  > 28|         if loginError.length > 0
    29|             p <strong>ERROR!</strong> #{ loginError }
    30|         label.sr-only(for="inputID") Student ID
    31|         input#inputID.form-control(type="text", name="userID", placeholder="User ID", required="", autofocus="")


Cannot read property 'length' of undefined
    at eval (eval at <anonymous> (C:\Users\Tai\AppData\Roaming\npm\node_modules\jade\lib\index.js:218:8), <anonymous>:11
4:16)
    at eval (eval at <anonymous> (C:\Users\Tai\AppData\Roaming\npm\node_modules\jade\lib\index.js:218:8), <anonymous>:19
5:22)
    at res (C:\Users\Tai\AppData\Roaming\npm\node_modules\jade\lib\index.js:219:38)
    at renderFile (C:\Users\Tai\AppData\Roaming\npm\node_modules\jade\bin\jade.js:270:40)
    at C:\Users\Tai\AppData\Roaming\npm\node_modules\jade\bin\jade.js:136:5
    at Array.forEach (native)
    at Object.<anonymous> (C:\Users\Tai\AppData\Roaming\npm\node_modules\jade\bin\jade.js:135:9)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)

我的代码如下,我将非常感谢任何帮助,但如果有人能解释我做错了什么,我会更喜欢它(或者至少链接到我可以了解如何使用 connect-flash 的东西)

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var mongojs = require('mongojs');
var db = mongojs('advisingApp', ['advisingApp']);
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var flash = require('connect-flash');

var app = express();

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


// 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(cookieParser('secretString'));
app.use(
  session({
    secret: 'secretKeyCookie',
    resave: true,
    saveUninitialized: true
  })
);
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

//All custom codes go after this comment line
app.use(function (req, res) {
  // flash a message
  req.flash('info', 'hello!');
  next();
})
app.all('/test', function(req, res){
  res.send(JSON.stringify(req.flash('test')));
});
app.post("/loginSuccess", function (req, res) {
  console.log("POST Request Received");
  console.log(req.body.userID);
  console.log(req.body.userPIN);
  db.advisingApp.find({ 'studentID': req.body.userID,'PIN': parseInt(req.body.userPIN)
  }, function(err, docs) {
    if(err) {
      console.log(err);
      return err;
    }
    else if(!docs || docs.length == 0) {
      console.log("User was not found!");
      var msg = "Your username and/or password was incorrect. Please try again.";
      res.error(msg);
      res.render("/", { loginError : req.flash('info')});
    }
    else {
      console.log(docs);
      res.render("home");
    }
    //res.send(docs);
  });
});

// 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;

翡翠

doctype html
html(lang="en")
  head
    meta(charset="utf-8")
    meta(http-equiv="X-UA-Compatible", content="IE=edge")
    meta(name="viewport", content="width=device-width, initial-scale=1")
    // The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags
    meta(name="description", content="")
    meta(name="author", content="")
    link(rel="icon", href="favicon.ico")
    title Signin Template for Bootstrap
    // Bootstrap core CSS
    link(href="/stylesheets/bootstrap.min.css", rel="stylesheet")
    // Custom styles for this template
    link(href="/stylesheets/style.css", rel="stylesheet")
    // Just for debugging purposes. Don't actually copy these 2 lines!
    //if lt IE 9
      script(src="/javascripts/ie8-responsive-file-warning.js")
    // <script src="/javascripts/ie-emulation-modes-warning.js"></script>
    // HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries
    //if lt IE 9
      script(src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js")
      script(src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js")
  body
    .container
      form.form-signin(method="post", action="/loginSuccess")
        h2.form-signin-heading(style="text-align:center;") Please sign in
        if loginError.length > 0
            p <strong>ERROR!</strong> #{ loginError }
        label.sr-only(for="inputID") Student ID
        input#inputID.form-control(type="text", name="userID", placeholder="User ID", required="", autofocus="")
        label.sr-only(for="inputPIN") PIN:
        input#inputPIN.form-control(type="password", name="userPIN", placeholder="Password", required="")
        button.btn.btn-lg.btn-primary.btn-block(type="submit") Sign in
    // /container
    // IE10 viewport hack for Surface/desktop Windows 8 bug
    script(src="/javascripts/ie10-viewport-bug-workaround.js")
    //AngularJS CDN
    script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js")

【问题讨论】:

    标签: node.js express connect-flash


    【解决方案1】:

    您的代码中有几个错误。在继续之前,请通过 Express 指南 routingwriting middlewareusing middleware

    您错过了中间件函数中的 next 参数。并且添加flash消息的中间件也应该放在使用路由器的前面。 (我不知道routes路由器处理什么资源。)

    app.use(function (req, res, next) {
      req.flash('info', 'hello!');
      next();
    })
    
    app.use('/', routes);
    app.use('/users', users);
    

    我怀疑这个中间件没有被调用,因为上面的代码错误,所以 flash 消息永远不会设置。

    当响应被渲染时,如果 flash 消息不存在,loginError 将是未定义的。这就是您收到错误 Cannot read property 'length' of undefined 的原因。

    res.render("/", { loginError : req.flash('info')});
    

    所以在翡翠模板中你应该像这样测试loginError

    if loginError
        p <strong>ERROR!</strong> #{ loginError }
    

    【讨论】:

    • 谢谢!在在线观看了不同的指南后,我确实设法弄清楚了,所以我想我终于设法掌握了这个
    • 请分享您提到的指南
    猜你喜欢
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2015-07-17
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多