node.js ошибка: req.fla sh () требует сеансов - PullRequest
0 голосов
/ 20 апреля 2020

Я новичок в узле, кто-нибудь может мне помочь с этой проблемой сеанса? Это простое приложение, которое я пытался запустить локально. Ниже приведены сведения о коде и сообщениях об ошибках

BAPS. js (приложение. js)

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var ConsoleFileLogger = require('./helpers/ConsoleFileLogger');
var cookieParser = require('cookie-parser');
var flash = require('express-flash');
var sess = require('express-session');
var MySQLStore = require('express-mysql-session')(sess);
var expressValidator = require('express-validator');
var nodemailer = require('nodemailer');
var passport = require('passport');
var bodyParser = require('body-parser');
var device = require('express-device');
var helmet = require('helmet');
var acl = require('express-acl');
var async = require('async');
var helpers = require('./routes/config/helpers');
const https = require("https"),
  fs = require("fs");
var mysql = require('mysql');
var app = express();

//get environment variables
const result =  require('dotenv').config({path: '/dotenv/.env'});
if(result.error){
  throw result.error;
}

// View engine setup
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(__dirname + '/public/images/favicon.ico'));

app.use(device.capture());
app.use(helmet());
app.use(logger('dev'));
app.use(logger('common', {
  stream: fs.createWriteStream(path.join(__dirname, '/logs/access_'+ConsoleFileLogger.createDateTimeFileName()+'.log'), { flags: 'a' })
}));
app.use(bodyParser.json({
  limit: '10mb'
}));
app.use(bodyParser.urlencoded({
  extended: true,
  limit: '10mb'
}));
app.use(flash());
app.use(cookieParser());
app.use(expressValidator());

var connection = require('./connection');

//Store sessions on database
var sessionStore = new MySQLStore({}, connection);

app.use(sess({
  name: 'BAPSSESSION',
  secret: 'BAPSISGREAT',
  secure: true,
  store: sessionStore,
  resave: true,
  saveUninitialized: true,
  cookie: {
    //TODO: CHANGE THIS BACK TO 1000000000!
    maxAge: 365 * 24 * 60 * 60 * 1000 //one year
  }
}));

//Passport config(authentication)
require('./routes/config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());

//Set default port
var port = process.env.PORT;
if(port == null)
{
  ConsoleFileLogger.error("didn't read the port");
}

if(process.env.ENVIRONMENT != "local")
{
  const options = {
    key: fs.readFileSync(process.env.KEY_PATH || "localhost.key"),
    cert: fs.readFileSync(process.env.CERT_PATH || "localhost.crt"),
    dhparam: fs.readFileSync(process.env.DH_STRONG_PATH || "dh-strong.pem")
  };

  https.createServer(options, app).listen(port);
}
else
{
  app.listen(port);
}

//Route files
var userData = require('./routes/userData');
var dashboard = require('./routes/dashboard');
var dashboardNewUser = require('./routes/dashboardNewUser');
var dashboardNewSchool = require('./routes/dashboardNewSchool');
var dashboardNewItem = require('./routes/dashboardNewItem');
var dashboardEditSchool = require('./routes/dashboardEditSchool');
var dashboardEditUser = require('./routes/dashboardEditUser');
var dashboardEditItem = require('./routes/dashboardEditItem');
var dashboardDeleteUser = require('./routes/dashboardDeleteUser');
var dl_database = require('./routes/dl_database');
var dashboardDeleteItem =require('./routes/dashboardDeleteItem');
var dashboardDeleteSchool = require('./routes/dashboardDeleteSchool');



//Set routes
app.use('/userData', userData);
app.use('/dashboard', dashboard);
app.use('/dashboard/dashboardNewUser', dashboardNewUser);
app.use('/dashboard/dashboardNewSchool', dashboardNewSchool);
app.use('/dashboard/dashboardNewItem', dashboardNewItem);
app.use('/dashboard/dashboardEditSchool', dashboardEditSchool);
app.use('/dashboard/dashboardEditUser', dashboardEditUser);
app.use('/dashboard/dl_database', dl_database);
app.use('/dashboard/dashboardEditItem', dashboardEditItem);
app.use('/dashboard/dashboardDeleteUser', dashboardDeleteUser);
app.use('/dashboard/dashboardDeleteItem', dashboardDeleteItem);
app.use('/dashboard/dashboardDeleteSchool', dashboardDeleteSchool);

//Print App Version
ConsoleFileLogger.log("Running BAPS Version: " + process.env.npm_package_version);

app.get('/', function(req, res) {
  res.render('login/index');
});

// =============================================================================
// Login
// =============================================================================
app.post('/', function(req, res, next) {
  //Desktop Login
  if (req.device.type == 'desktop') {
    passport.authenticate('local', {
      successRedirect: '/dashboard',
      failureRedirect: '/',
      badRequestMessage: 'Please, provide credentials',
      failureFlash: true
    })(req, res, next);
  } else {
    passport.authenticate('local', {
      successRedirect: '/login_tablet_success',
      failureRedirect: '/failed_login_tablet',
      badRequestMessage: 'Please, provide credentials',
      failureFlash: true
    })(req, res, next);
  }
});

app.get('/login_tablet_success', function(req, res) {
  res.json({
    userData: [{
      'message': 'Succesful login',
      loginSuccess: 1
    }, {
      userId: req.user.id,
      userName: req.user.name,
      userLastName: req.user.lastName,
      userEmail: req.user.email,
      userLabel: req.user.label
    }]
  });
});

app.get('/failed_login_tablet', function(req, res) {
  res.json({
    userData: [{
      message: req.flash().error[0],
      loginSuccess: 0
    }]
  });
});

app.get('/logout', function(req, res) {
  req.session.destroy(function(err) {
    if (err) {
      ConsoleFileLogger.error("error: " + err);
    } else {
      if (req.device.type == 'desktop') {
        res.redirect('/');
      } else {
        res.json({
          'message': 'Logged out succesfully'
        });
      }
    }
  });
});

// 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 handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Сообщение об ошибке с терминала:

Рабочая версия BAPS : 3.2.4 GET / 500 5.523 мс - 1396 Ошибка: для req.fla sh () требуются сеансы в IncomingMessage._fla sh [как flash] (/ Users / chrischen / Documents / BAPS / baps_rest / node_modules / connect- flash / lib / fla sh. js: 60: 41) на ServerResponse.res.render (/ Users / chrischen / Documents / BAPS / baps_rest / node_modules / express -flash / lib / express -fla sh. js: 28: 35) в /Users/chrischen/Documents/BAPS/baps_rest/BAPS.js:239:7 в Layer.handle_error (/ Users / chrischen / Documents / BAPS / baps_rest / node_modules /express/lib/router/layer.js:71:5) в trim_prefix (/Users/chrischen/Documents/BAPS/baps_rest/node_modules/express/lib/router/index.js:315:13) в /Users/chrischen/Documents/BAPS/baps_rest/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/ Users / chrischen / Documents / BAPS / baps_rest / node_modules / express / lib / маршрутизатор /index.js:335:12) на следующем (/Users/chrischen/Documents/BAPS/baps_rest/node_modules/express/lib/router/index.js:275:10) на Layer.handle_error (/ Users /chrischen/Documents/BAPS/baps_rest/node_modules/express/lib/router/layer.js:67:12) в trim_prefix (/ Users / chrischen / Documents / BAPS / baps_rest / node_modules / express / lib / router / index . js: 315: 13)

1 Ответ

1 голос
/ 20 апреля 2020

Попробуйте переместить app.use(flash()); после

app.use(sess({
  name: 'BAPSSESSION',
  secret: 'BAPSISGREAT',
  secure: true,
  store: sessionStore,
  resave: true,
  saveUninitialized: true,
  cookie: {
    //TODO: CHANGE THIS BACK TO 1000000000!
    maxAge: 365 * 24 * 60 * 60 * 1000 //one year
  }
}));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...