如何在其他JavaScript文件expressjs中使用req.session数据 [英] How to use req.session data in an other javascript file expressjs

查看:49
本文介绍了如何在其他JavaScript文件expressjs中使用req.session数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了很长时间才真正不知道如何访问会话数据.当用户登录到应用程序时,其ID和名称将保存在req.session中.

Hours of trying I really don't know how to access session data. When a user is logged in the application the id and name is saved in req.session.

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脚本.它不是任何路线,也不是任何东西,但这就是我需要获取用户ID的地方.

And i have a game.js script. it isn't in any route or anything but thats the place where i need to get the userid.

这是用户的中间件

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中,我需要有权访问会话数据.

So this is all i have. so i have this game.js script. and in that javascript i need to have access to the session data.

推荐答案

在没有大量黑客攻击的情况下,当前的设置是不可能的.每个会话都依赖于在请求的cookie中找到的用户的SID.因此,会话被牢固地耦合到请求对象.您将必须找到一种聪明的方法来通过中间件初始化 game.js 模块.像这样:

This is not possible with your current setup without a lot of hacking. Each session is reliant on the user's SID found in the request's cookie. Thus, the session is strongly coupled to the request object. You will have to find a clever way to initialize your game.js module through middleware. Something like:

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

希望能帮助您到达那里.我的诚实观点是,您可能需要重新考虑设计,因为不能直接与请求对象一起使用的模块不应与请求对象紧密结合.

Hope that helps you get there. My honest opinion is that you might want to reconsider your design as your modules that don't work with the request object directly shouldn't be tightly coupled with the request object.

这篇关于如何在其他JavaScript文件expressjs中使用req.session数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆