简体   繁体   English

将res res对象传递给socket.io?

[英]Pass req res objects into socket.io?

I am a little confused how I can interact with the socket when I need to pass in data from my routes file. 当我需要从路由文件中传递数据时,我有点困惑如何与套接字交互。 I have the standard setup using node.js, express, mongodb etc. 我使用node.js,express,mongodb等进行标准设置。

I'll run my socket.io logic inside server.js, and I include the routes.js inside that file. 我将在server.js中运行我的socket.io逻辑,并将该route.js包含在该文件中。

var routes = require('./app/routes');

In this case I need to run some io.sockets inside my routes.js file. 在这种情况下,我需要在routes.js文件中运行一些io.sockets。

My question is what is a good way to do this? 我的问题是执行此操作的好方法是什么? I could run that specific route inside server.js but that gets messy. 我可以在server.js中运行该特定路由,但这会变得混乱。 If I were to use sockets in my routes.js do I need to re-require 如果我要在我的route.js中使用套接字,我是否需要重新请求

var io = require('socket.io').listen(server);

That means I need to create a new http server object, and I don't like that since I am requiring this file in server.js, this seems like a counter-intuitive move to me. 这意味着我需要创建一个新的http服务器对象,并且我不喜欢那样,因为我在server.js中需要此文件,对我来说这似乎是违反直觉的。

So how do I make a request to the server and pass for example a user name? 那么,如何向服务器发出请求并传递例如用户名呢?

Example: 例:

app.get('/profile', isLoggedIn, function(req, res) {

    res.render('profile', { user : req.user });

    io.sockets.on('connection', function (socket) {
        console.log(socket);
            console.log(req.user); // Here I have access to the user and can pass that around in                        my sockets
    });

});

I am also using route middleware, so I'd like to keep that in my routes.js, IDK I am just confused what I should do, hopefully someone understands my angle here? 我也在使用路由中间件,所以我想将其保留在我的routes.js中,IDK让我感到困惑,希望有人能理解我的观点?

Edit: 编辑:

What about passing something into the routes? 将某些东西传递给路线呢?

routes.initialize(app, passport);

You can get the req and res objects directly in the socket by invoking socket.request (a Getter function which is available via __proto__ ). 您可以通过调用socket.request (可通过__proto__获得的Getter函数)直接在套接字中获取reqres对象。 See docs . 参见docs

I was then able to find req.user in socket.request.client.user . 然后,我能够在req.user中找到socket.request.client.user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM