Node.js / Express request.session undefined?

时间:2014-01-02 16:55:58

标签: node.js session express

我有一个已经运行了几个月的节点/套接字/快速站点,而且突然间我只是在尝试加载主页时遇到错误。这是我的server.js文件:

var bugsnag = require("bugsnag");
bugsnag.register(KEY);
var Lobby = require('./lobby').Lobby
var express = require('express')
var engine = require('ejs-locals')
var app = express()
  , cookieParser = express.cookieParser('secret')
  , server = require('http').createServer(app)
  , cookie  =   require('cookie')
  , connect =   require('connect')
  , MemoryStore = connect.middleware.session.MemoryStore
  , sessionStore
  , io = require('socket.io').listen(server);

app.use(bugsnag.requestHandler);
app.use(express.static(__dirname+'/public'));
app.use(express.bodyParser());
app.use(cookieParser);
app.use(express.session({secret:'secret',key:'express.sid',store:sessionStore = new MemoryStore(),maxAge: 30*24*60*60*1000}));
app.use(bugsnag.errorHandler);

io.set('authorization', function (handshake, accept) {
  if (!handshake.headers.cookie) 
    return accept('No cookie transmitted.', false);
  handshake.cookie = cookie.parse(handshake.headers.cookie);
  cookieParser(handshake, {}, function(err) {
    if(handshake.signedCookies){
      handshake.sessionID = handshake.signedCookies['express.sid'];
      sessionStore.load(handshake.sessionID, function (err, session) {
        if (err)
          accept(err.message, false); //Turn down the connection
        else {
          handshake.session = session; //Accept the session
          accept(null, true);
        }
      });
    }
  });
});

var mysql = require('mysql');
var dbConnection;
app.configure('development', function(){
  dbConnection = mysql.createConnection({DEV_CONNECTION_STRING});
  io.set('log level', 3);
});

app.configure('production', function(){
  dbConnection = mysql.createConnection({PROD_CONNECTION_STRING});
  io.set('log level', 0);
});
dbConnection.connect(function(error){if(error){return console.log("CONNECTION error: "+error);}});

//var domain = require('domain');
app.engine('ejs', engine); // use ejs-locals for all ejs templates:
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')

var lobbya = new Lobby(io,dbConnection,'lobbya');
var lobbyz = new Lobby(io,dbConnection,'lobbyz');

server.listen(8080); //4000

require('./routes').addRoutes(app,dbConnection);

io.sockets.on('connection', function (socket) {clientConnect(socket)});

function clientConnect(socket) {
  var session = socket.handshake.session;
  if (session == null) {
    socket.emit('sign out');
    dbConnection.query("Insert into eventlog (type, details) values ('boot no session','"+JSON.stringify(session)+"');");    
  }
  else if (session.player == null) {
    socket.emit('sign out');
    dbConnection.query("Insert into eventlog (type, details) values ('boot no player','"+JSON.stringify(session)+"');");
  }
  else {
    socket.on('join room', function (room) {
      dbConnection.query("Insert into eventlog (type, details) values ('join room','"+room+":"+JSON.stringify(session)+"');");
      if (room == 'lobbya')
        lobbya.connect('',socket,session.player);
      else if (room == 'lobbyz')
        lobbyz.connect('',socket,session.player);
      else if (room.substring(0,5) == 'gamea') //join game, figure out which game
        lobbya.gameConnect('',socket,session.player,room.substring(5,room.length),sessionStore);
      else if (room.substring(0,5) == 'gamez') //join game, figure out which game
        lobbyz.gameConnect('',socket,session.player,room.substring(5,room.length),sessionStore); 
    });
  }
}

这是发生错误的路由文件的顶部:

var Simulator = require('./simulator').Simulator;
var email = require("emailjs/email");
var url = require('url');

exports.addRoutes = function(app, dbConnection) {
  app.get('/', function(request,response){
    dbConnection.query("SELECT sum(games_finished) as games, max(longest_win_streak) as streak, max(games_won) as wins FROM players;",
    function (error, results, fields) {
      var games = Math.ceil(results[0]['games']/2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      var streak = results[0]['streak'].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      var wins = results[0]['wins'].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      dbConnection.query("SELECT p1.username as user1, p2.username as user2, gl.player1_score, gl.player2_score, DATE_FORMAT(gl.created_at - INTERVAL 8 hour, '%b %e %l:%i %p') as created_at FROM gamelog gl join players p1 on gl.player1_id = p1.id join players p2 on gl.player2_id = p2.id where gl.end_type = 'pegout' ORDER BY gl.created_at DESC limit 3;",
       function (error, results, fields) { 
        latestResults = [];
        for (var i=0; i<results.length; i++) {
          if (results[i]['player1_score'] > results[i]['player2_score'])
        latestResults[i] = results[i]['created_at'] + ' - ' + results[i]['user1']+' def. '+results[i]['user2']+' 121-'+results[i]['player2_score'];
          else
            latestResults[i] = results[i]['created_at'] + ' - ' + results[i]['user2']+' def. '+results[i]['user1']+' 121-'+results[i]['player1_score'];
        }
        response.render('index', { player: request.session.player , error: '', room: '', games: games, streak: streak, wins: wins, latestResults: latestResults });
      });
    });
  });
}

渲染“索引”ejs时发生错误,错误与request.session.player有关。具体来说,“无法读取未定义的属性'播放器'”

我不明白会话是如何定义的?这在我当地没有发生。是因为它拒绝了代码中io.set('authorization')部分的握手?如果是这样,如果在该部分代码中拒绝该握手,那么正确的做法是什么?

0 个答案:

没有答案