如何在ExpressJS中跨多个路由JS文件共享Session

时间:2016-12-02 04:18:05

标签: node.js express express-session

首先,我正在使用:

  • express-session@1.14.2
  • express@4.14.0

我基本上试图让登录系统正常工作,当用户登录时,我设置了session.isloggedin = true。

所以这是我的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 session = require('express-session');

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

var app = express();

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

// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

// 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());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true,
            maxAge: new Date(Date.now() + 2 * 60 * 1000) }
}));

app.use('/', index);
app.use('/portfolio', portfolioRoute);

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

index.html包含登录表单。

接下来,我的index.js

var express = require('express');
var router = express.Router();
var util = require('util');
var api = require('../server/api.js');
var port = require('../server/portfolio.js');

var sess;

/* GET home page. */
router.get('/', function (req, res) {
  sess = req.session;
  console.log("SESSION IS: " + sess.isLoggedIn);
  if(sess.isLoggedIn) {
    res.render('portfolio', { isLoggedIn: true })
  } else {
    res.render('index', { isLoggedIn: false })
  }
})
//END ------------

if(global.GLB_PORTFOLIO === null) {
  port.getPortfolio(null, function(err, result) {
    global.GLB_PORTFOLIO = result;
  });
}

// API Routes
//router.use('/api', router);
router.route('/api/login')
  .post(api.postLogin)
router.route('/api/portfolio')
  .post(api.postPortfolio)
  .get(api.getPortfolio)
//END ------------

module.exports = router;

接下来,我的api.js:

var util = require('util');
const backend = require('./portfolio.js');

exports.postPortfolio = function(req,res) {
  backend.insertPortFolio(req.body, function(err, result) {
    res.json({ result: result, error:err });
  });
}

exports.getPortfolio = function(req,res) {
  backend.getPortfolio(req, function(err, result) {
    global.GLB_PORTFOLIO = result;
    res.json({ portfolio: result, error: err });
  });
}

exports.postLogin = function(req,res) {
  backend.findUserByEmail(req.body.email, function(err, result) {
    console.log("API: SESSION IS: " + req.session.isLoggedIn);
    if(err || result === null) {
      req.session.isLoggedIn = false;
    } else {
      req.session.isLoggedIn = true;
    }
    req.session.save();
    res.json({ user: result, error: err });
  });
}

即使在save()之后,会话变量也始终未定义。我做错了什么?

0 个答案:

没有答案