2013-12-16 29 views
0

嘗試幾小時我真的不知道如何訪問會話數據。當用戶登錄該應用程序時,ID和名稱將保存在req.session中。如何在其他javascript文件中使用req.session數據expressjs

exports.form = function (req, res) { 
    res.render('login', { 
     title: 'Login' 
    }); 
}; 
var User = require('../lib/user'); 
exports.submit = function (req, res, next) { 
    var data = req.body.user; 
    User.authenticate(data.name, data.pass, function (err, user) { 
     if (err) return next(err); 
     if (user) { 
      req.session.uid = user.id; 
      req.session.username = user.name; 
      res.redirect('/index'); 
     } else { 
      res.error("Sorry! invalid credentials."); 
      res.redirect('back'); 
     } 
    }); 
}; 
exports.logout = function (req, res) { 
    req.session.destroy(function (err) { 
     if (err) throw err; 
     res.redirect('/'); 
    }) 
}; 

這是app.js

var express = require('express'); 
var routes = require('./routes'); 
var path = require('path'); 
var index = require('./routes/index'); 
var register = require('./routes/register'); 
var messages = require('./lib/messages'); 
var login = require('./routes/login'); 
var user = require('./lib/middleware/user'); 
var requireLogin = require('./lib/middleware/logedIn'); 
var api = require('./routes/api'); 

var 
    gameport  = process.env.PORT || 4004, 

    io    = require('socket.io'), 
    express   = require('express'), 
    UUID   = require('node-uuid'), 

    verbose   = false, 
    http   = require('http'), 
    app    = express(), 
    server   = http.createServer(app);  
    app.set('port', process.env.PORT || 3000); 
    app.set('views', __dirname + '/views'); 
    app.set('view engine', 'ejs'); 
    app.use(express.favicon()); 
    app.use(express.logger('dev')); 
    app.use(express.bodyParser()); 
    app.use(express.methodOverride()); 
    app.use(express.cookieParser('your secret here')); 
    app.use(express.session()); 
    app.use(express.static(__dirname + '/public')); 
    app.use(user); 
    app.use(messages); 
    app.use(app.router); 
    //app.use('/index', requireLogin); 

    app.get('/index', requireLogin.auth, function (req, res) 
    { 
     //app.get('/index'); 
     res.render('index', { title: 'Express' }); 
    }); 
    app.get('/register', register.form); 
    app.post('/register', register.submit); 
    app.get('/login', login.form); 
    app.post('/login', login.submit); 
    app.get('/logout', login.logout); 
    app.get('/api/user/:id', api.user); 

server.listen(gameport) 

    //Log something so we know that it succeeded. 
console.log('\t :: Express :: Listening on port ' + gameport); 

    //By default, we forward the/path to index.html automatically. 
app.get('/', function(req, res){ 
    console.log('trying to load %s', __dirname + '/index.html'); 
    res.sendfile('/index.html' , { root:__dirname }); 
}); 


    //This handler will listen for requests on /*, any file from the root of our server. 
    //See expressjs documentation for more info on routing. 

app.get('/*' , function(req, res, next) { 

     //This is the current file they have requested 
    var file = req.params[0]; 

     //For debugging, we can track what files are requested. 
    if(verbose) console.log('\t :: Express :: file requested : ' + file); 

     //Send the requesting client the file. 
    res.sendfile(__dirname + '/' + file); 

}); //app.get * 

    //Create a socket.io instance using our express server 
var sio = io.listen(server); 

    //Configure the socket.io connection settings. 
    //See http://socket.io/ 
sio.configure(function(){ 

    sio.set('log level', 0); 

    sio.set('authorization', function (handshakeData, callback) { 
     callback(null, true); // error first callback style 
    }); 

}); 

    //Enter the game server code. The game server handles 
    //client connections looking for a game, creating games, 
    //leaving games, joining games and ending games when they leave. 
game_server = require('./game.server.js'); 

    //Socket.io will call this function when a client connects, 
    //So we can send that client looking for a game to play, 
    //as well as give that client a unique ID to use so we can 
    //maintain the list if players. 
sio.sockets.on('connection', function (client) { 

     //Generate a new UUID, looks something like 
     //5b2ca132-64bd-4513-99da-90e838ca47d1 
     //and store this on their socket/connection 
    client.userid = UUID(); 

     //tell the player they connected, giving them their id 
    client.emit('onconnected', { id: client.userid }); 

     //now we can find them a game to play with someone. 
     //if no game exists with someone waiting, they create one and wait. 
    game_server.findGame(client); 

     //Useful to know when someone connects 
    console.log('\t socket.io:: player ' + client.userid + ' connected'); 


     //Now we want to handle some of the messages that clients will send. 
     //They send messages here, and we send them to the game_server to handle. 
    client.on('message', function(m) { 

     game_server.onMessage(client, m); 

    }); //client.on message 

     //When this client disconnects, we want to tell the game server 
     //about that as well, so it can remove them from the game they are 
     //in, and make sure the other player knows that they left and so on. 
    client.on('disconnect', function() { 

      //Useful to know when soomeone disconnects 
     console.log('\t socket.io:: client disconnected ' + client.userid + ' ' + client.game_id); 

      //If the client was in a game, set by game_server.findGame, 
      //we can tell the game server to update that game state. 
     if(client.game && client.game.id) { 

      //player leaving a game should destroy that game 
      game_server.endGame(client.game.id, client.userid); 

     } //client.game_id 

    }); //client.on disconnect 

}); //sio.sockets.on connection 

,我有一個game.js腳本。它不在任何路線或任何東西,但那是我需要獲得用戶名的地方。

這對於用戶

var User = require('../user'); 

module.exports = function(req, res, next) 
{ 
var uid = req.session.uid; 
if(!uid) return next(); 
User.get(uid, function(err, user) 
{ 
    if(err) return next(err); 
    req.user = res.locals.user = user; 
    next(); 
}); 
}; 

德中間件所以這是我的全部。所以我有這個game.js腳本。並在該JavaScript我需要訪問會話數據。

+0

只要包含會話中間件,您就可以在請求作爲參數的回調中以同樣的方式訪問它。 – adeneo

+0

你可以發佈你的中間件設置?只要中間件堆棧配置正確,所有路由中間件都應該有權訪問'req.session'對象。 – srquinn

+0

我添加了app.js和user.js,我希望你能幫我解決 – Julien

回答

1

這是不可能與您的當前設置沒有大量的黑客攻擊。每個會話都依賴於請求cookie中找到的用戶的SID。因此,會話強烈地耦合到請求對象。您將不得不尋找一種巧妙的方式來通過中間件初始化您的game.js模塊。喜歡的東西:

var Game = require('./game'); 

// -- Place this AFTER your session middleware 
app.use(function (req, res, next) { 
    req.game = new Game(req); 
    next(); 
}); 

然後裏面的game.js

var Game = module.exports = function (req) { 
    // do stuff with req.session here 
    this.req = req; 
} 

Game.prototype.getSessionID = function() { 
    return this.req.session.uid; 
} 

希望幫助你到達那裏。我誠實的看法是,你可能想重新考慮你的設計,因爲你的模塊不直接與請求對象一起工作,不應該與請求對象緊密耦合。

+0

在app.js中我找到了下面的代碼client.userid = UUID(); //告訴玩家他們連接,給他們他們的ID client.emit('onconnected',{id:client.userid});所以實際上我現在需要做的是在app.js中獲取會話,並將其作爲client.id – Julien

0

好吧,我做了一些事情來解決我的問題。我真的覺得很難,而且很簡單。

當用戶需要驗證自己我保存會話變量。

app.get('/index', requireLogin.auth, function (req, res) 
    { 
     username = req.session.username; 
     userid = req.session.uid; 
     req.session.username = req.param('username'); 
     res.render('index', { title: 'Express' }); 
    }); 

在sio.connection中有一個函數用於將遊戲的用戶標識和名稱添加到遊戲中。

sio.sockets.on('connection', function (client, req) { 

     //Generate a new UUID, looks something like 
     //5b2ca132-64bd-4513-99da-90e838ca47d1 
     //and store this on their socket/connection 
    client.userid = userid; 
    client.username = username; 
+0

我看到的唯一問題是,您使用的變量是全局的'app.js'文件你會發現自己處於狀態維護的噩夢。特別是如果你的代碼庫增長,你想分裂成多個文件。 – srquinn

+0

你有什麼建議嗎? – Julien

+0

查看上面的代碼,是否無法訪問sio事件偵聽器回調中的會話中間件? la'req.session'? – srquinn

相關問題