如何在其他javascript文件expressjs中使用req.session数据
几个小时的尝试我真的不知道如何访问会话数据。当用户登录应用程序时,id和名称保存在req.session中如何在其他javascript文件expressjs中使用req.session数据,javascript,node.js,express,Javascript,Node.js,Express,几个小时的尝试我真的不知道如何访问会话数据。当用户登录应用程序时,id和名称保存在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.
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的地方
这是用户的de中间件
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中,我需要访问会话数据。如果没有大量的黑客攻击,在当前设置中这是不可能的。每个会话都依赖于在请求的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;
}
希望这能帮助你到达那里。我真诚的意见是,您可能需要重新考虑您的设计,因为不直接与请求对象一起工作的模块不应该与请求对象紧密耦合。好的,我做了一些事情来解决我的问题。我真的觉得很难,也很简单
当用户需要对自己进行身份验证时,我保存会话变量
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;
只要包含会话中间件,您就可以在回调中以请求作为参数以相同的方式访问它。您可以发布中间件设置吗?只要中间件堆栈配置正确,所有路由中间件都应该可以访问req.session
对象。我添加了app.js和user.js,希望你能帮助我在app.js中找到下一个代码client.userid=UUID()//告诉玩家他们连接了,给他们id client.emit('onconnected',{id:client.userid});因此,实际上我现在需要做的是在app.js中获取会话,并将其作为client.id提供。我看到的唯一问题是,您使用的变量是app.js
文件的全局变量,您将发现自己处于状态维护噩梦中。特别是如果代码库不断增长,并且希望拆分为多个文件,您有什么建议吗?查看上面的代码,您是否无法访问sio事件侦听器回调中的会话中间件?lareq.session
?我还想在这里了解如何使用socket.io设置授权,它描述了一种比当前更好的设置