7

nodejs(0.8.15)、express(> 3.0)フレームワーク、および登録ユーザー用のmongodbを使用して、チャットアプリケーションを作成しています。

var express = require('express')
  , http = require('http')
  , path = require('path')
  , io = require('socket.io');

var app = express()
  , server = http.createServer(app)
  , io = io.listen(server);

    app.configure(function() {
      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('secret'));
      app.use(express.session({cookie: {maxAge: 60000*100}}));
      app.use(app.router);
      app.use(express.static(path.join(__dirname, 'public')));
    });

    app.configure('development', function() {
      app.use(express.errorHandler());
    });

    app.get('/chat', function(req, res) {
        res.render('chat');
    });

 server.listen(app.get('port'), function() {
    console.log("Express server listening on port " + app.get('port'));
  });

 io.sockets.on('connection', function (socket) {
    socket.on('start-chat', function() {
         // here i need to know req and res
         // for example, i need to write:
         // socket.username = req.session.username;
    });
 });

Q: 上記のコードのようにチャットしているときに res オブジェクトと req オブジェクトを操作するにはどうすればよいですか? または、ユーザー認証でチャットを作成する方法が間違っていますか?

ありがとう!

EDITED:答えはここにあり ます http://www.danielbaulig.de/socket-ioexpress/

4

3 に答える 3

7

を使用する必要がありますauthorization

var socketIO = require('socket.io').listen(port);
socketIO.set('authorization', function(handshakeData, cb) {
   //use handshakeData to authorize this connection
   //Node.js style "cb". ie: if auth is not successful, then cb('Not Successful');
   //else cb(null, true); //2nd param "true" matters, i guess!!
});

socketIO.on('connection', function (socket) {
   //do your usual stuff here
});
于 2013-10-11T17:08:40.193 に答える
6

res オブジェクトと req オブジェクトは socket.io ハンドラーで取得できません。それらは単に存在しないためです。socket.io は通常の http ではありません。

代わりに、ユーザーを認証し、セッション認証トークン (ユーザーがログインしていることとユーザーが誰であるかを識別するキー) を割り当てることができます。その後、クライアントはすべての socket.io メッセージとともに認証トークンを送信でき、サーバー側のハンドラーはデータベース内のキーの有効性を確認できます。

io.sockets.on('connection', function (socket) {
socket.on('start-chat', function(message) {
     if (message.auth_token)
         //Verify the auth_token with the database of your choice here!
     else
         //Return an error message "Not Authenticated"
});
于 2012-11-28T22:51:59.580 に答える
-2

以上で、このようなオブジェクトsocket.io v1.0を取得できますreq

var req = socket.request;
var res = req.res;
于 2016-05-26T12:20:50.970 に答える