4

我对 node.js 和 express 还很陌生,我正在尝试通过电话间隙构建一个相当简单的应用程序,它允许我进行用户登录,并将用户的套接字 id 保存到会话中,这样我就可以跟踪哪个用户是什么 id,所以我只能向特定的用户组发送消息(它是一个游戏,所以我需要向玩家 1 和玩家 2 发送消息,我猜玩家是成对的吗?)

我有以下 index.js 文件,这是我的观点。我似乎无法让它按我想要的方式工作,并且当我请求 /login 时,我无法在视图中看到用户名。它只是显示为空白字符串或未定义。

我尝试了以下事情:

1) 在表单提交时有一个套接字发射,然后在 socket.on('form_submit_done') 回调中,我会调用一个 javascript 表单发布到登录名,然后它将检查我的 mongodb 是否有该用户,如果有效,转到游戏空间页面。这一直有效,直到我开始使用 socket.io

2)我已经更新它来处理套接字本身内的 db 调用。在我的服务器上,我进行数据库检查,然后发回给客户端。根据我发出的内容,我做了一个特定的 window.location.replace(); 我确信必须有一种更简单的方法来做到这一点,但我似乎无法弄清楚。

谁能给我一些我可以遵循的指示或教程,这将使这更容易理解?

index.js

/*jshint laxcomma:true*/

var io = require('socket.io')
  , express = require('express')
  , util = require('util')
  , app = express.createServer()
  , connect = require('express/node_modules/connect')
  , parseCookie = connect.utils.parseCookie
  , MemoryStore = connect.middleware.session.MemoryStore
  , store;


  //middleware 
  app.use(express.bodyParser());


app.configure(function () {
  app.set('views', __dirname + '/views');
  app.use(express.static(__dirname + '/public'));
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(express.cookieParser());
  app.use(express.session({
      secret: 'secret'
    , key: 'express.sid'
    , store: store = new MemoryStore()
  }));
});


/* ==============================================================
*         Database Setup        *
*                 *
* ==============================================================*/
var mong = require('mongoose');
mong.connect('mongodb://127.0.0.1:27017/bravazzo');

var db = mong.connection; 
db.on('error', console.error.bind(console, 'connection error')); 
db.once('open', function callback(){
  console.log("db connection good"); 
});

// database schemas for the mongo db.

var userSchema = new mong.Schema({
  user_name:String, 
  email:String, 
  password:String,
  last_login:Date
});

var game_schema = new mong.Schema({
  _id:{type:Number}, 
  player_1: [mong.Schema.Types.ObjectId], 
  player_2:[mong.Schema.Types.ObjectId],  
  date: Date,
  winner:[mong.Schema.Types.ObjectId]
})

// putting models into variables.
// type = mong.model('name in mongo', schemaName);
var user = mong.model('users', userSchema);
var game = mong.model('games', game_schema);


/* ================================================================
*               Misc Functions                                    
*
* ================================================================*/


app.get('/', function (req, res) {
  res.render('splash', {value: req.session.value});
});

// handle the login post action here.
app.get("/login", function(req, res){
    app.use(express.bodyParser());
    console.log(req);
    res.render('game_dashboard', {pageData: {name: req.session.userName}});
});



app.listen(8080);

io.listen(app).set('authorization', function (data, accept) {
  if (!data.headers.cookie) 
    return accept('No cookie transmitted.', false);

  data.cookie = parseCookie(data.headers.cookie);
  data.sessionID = data.cookie['express.sid'];

  store.load(data.sessionID, function (err, session) {
    if (err || !session) return accept('Error', false);

    data.session = session;
    return accept(null, true);
  });
}).sockets.on('connection', function (socket) {
  var sess = socket.handshake.session;
  socket.log.info(
      'a socket with sessionID'
    , socket.handshake.sessionID
    , 'connected'
  );
  socket.on('go login', function (data) {
    // let us check the login credentials!
    var pwd = data.password;
    var uName = data.userName; 
    // this should be refactored at some point where it does the following:
    // look for username, if can't found redirect with message.
    // if uname is good, check password, if wrong, send to page w/ message
    // incorrect password.
    // else everything is good.
    user.find({user_name:uName, password:pwd }).exec(function(err,results){
      if (!err && results.length > 0){
        // we looged in! good.
        sess.reload(function(){
          sess.value = data.random; 
          sess.userName = uName;
          sess.touch().save();
        });
        socket.emit('login_post', {number: data.ran, data:data, user: uName });
    }
    else{
        socket.emit('login_post',{number:data.ran, data:'splash'});
      }
    }); // end user.find
  }); // send socket.on go login
}); // end on connection

飞溅.jade

!!! 5
html
  head
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1')
    title="Bravazzo"
    link(rel='stylesheet', href='css/user-styles.css')
    link(rel='stylesheet', href='css/bootstrap.min.css')
    link(rel='shortcut icon', href='favicon.ico')
    link(rel='stylesheet', href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,700')
    script(src='js/jquery.js')
    script(src='/socket.io/socket.io.js')
    script(src='http://code.jquery.com/jquery-latest.js')
    script(src='/js/client.js')
  body
    .splash_spacer
      if value
        h2 your session is #{value}
      else
        h2 set session value !
      form(name='login', type="application/x-www-form-urlencoded", id='login_form', action='/login',method='post')
      .pad_left
        label  Username:
        input(type="text", name="userName")
      .pad_left
        label  Password:
        input(type="password", name="password")
        input(type="hidden", id="random", name="random")
      br
      .pad_left_long
        a(href='/register', class="btn btn-inverse", style="width:55px") Sign Up

          
        input(type="submit", value="Login ",id="login", class="btn btn-inverse" style="width:77px;")
script.
  var socket = io.connect(); 
  var sub = $('#login');
  var randomnumber=Math.floor(Math.random()*1001)

  sub.click(function (e){
    socket.emit('go login',{
      userName: $('#userName').val(),
      password: $('#password').val(),
      ran: randomnumber
    });
  });

  socket.on('login_post', function(data){
    console.log(data.number); 
    console.log(randomnumber);
    if (data.data == 'splash'){
      window.location.replace('/');
    }
    if (data.number == randomnumber)
      window.location.replace('/login');
  });
4

1 回答 1

3

您可以使用会话套接字模块模块能够:

  • 保存和检索每个用户的会话信息
  • 获取所有连接的用户及其会话信息
于 2014-01-16T15:39:34.843 回答