在expressjs路由中使用socket.io而不是在main server.js文件中 [英] Use socket.io in expressjs routes instead of in main server.js file

查看:108
本文介绍了在expressjs路由中使用socket.io而不是在main server.js文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表达/ nodejs api。我正在添加socket.io功能。目前我的所有路由都在单独的文件夹中,我将它们包含在server.js文件中,并将它们用作app.use()函数。

I have express/nodejs api. I am adding socket.io feature to it. Currently all of my routes are in separate folders and I include them in server.js file and use them as app.use() function.

在server.js文件中,我也通过监听特定端口(如下面的3000)启动快速服务器。

In server.js file, I also start the express server by listening to a particular port such as 3000 as below.

let server = app.listen(3000);

根据所有谷歌搜索,我发现我需要传递服务器变量来初始化socket.io喜欢以下。

According to all google searches what I found is that I need to pass server variable to initialize socket.io like following.

let io = require('socket.io')(server);

现在的问题是,因为它需要这个变量,那我怎么能在我的路线中使用socket.io文件位于不同的文件夹中以发出和接收来自客户的事件?

Now the question is that since it needs this variable then how can I use socket.io in my routes files which are in different folder to emit and receive events from client?

更新

在server.js文件中

in server.js file

let route = require('./routes/route');

let app = express();

let server = app.listen(3000);

console.log('Listening to port');

let io = require('socket.io')(server);

app.use('/api/1.0/events', route(io));

let express = require('express');

module.exports = (io) => {
    console.log('IO: ', io);
};

更新2

server.js file

server.js file

let express = require('express');
let events = require('./routes/events');
let app = express();
let server = app.listen(3000);

let io = require('socket.io')(server);


app.use(function(request, response, next) {
    request.io = io;
    next();
});

app.use('/events', events);

events.js file

events.js file

let express = require('express');

let Events = require('../models/events');

apiRoutes.post('/new', function(request, response) {
    let newEvent = new Events(request.body);

    newEvent.save((error, result) => {
        if (error) {
            response.json(error);
        } else {
            // console.log('ELSE');
            // request.io.on('connect', socket => {
                // console.log('LISTENING TO SOCKET...');

                request.io.on('EventCreated', data => {
                    console.log('DATA ON Server: ', data);
                });
            // });

            response.json({
                success: true,
                message: 'New event created'
            });
        }
    });
});


推荐答案

有多种方式可以分享 io 带路径文件的变量。

There are multiple ways to share the io variable with route files.


  1. 当你 require时( )在您的路径文件中,将 io 变量作为构造函数参数传递给它。

  1. When you require() in your route file, pass it the io variable as a constructor argument.

使用 app.set(io,io),这样你就可以使用 let io = app.get(io) 在任何可以访问 app 对象的文件中。

Use app.set("io", io) so you can then use let io = app.get("io") in any file that has access to the app object.

创建一个中间件,它在每个 req 对象上放置 io 对象,这样你就可以随时从那里访问它。

Create a middleware that puts the io object on every req object so you can access it from there any time.






以下是将其作为构造函数参数传递给路由器文件的示例:


Here's an example of passing it as a constructor argument to the router file:

let server = app.listen(3000);
let io = require('socket.io')(server);

// load other routers
app.use(require("./someRouterFile.js")(io));

// in someRouterFile.js
const express = require('express');

module.exports = function(io) {
    let router = express.Router()

    // define routes
    // io is available in this scope
    router.get(...)

    return router;
}






这是一个例子 app.set() scheme:

let server = app.listen(3000);
let io = require('socket.io')(server);
app.set("io", io);

然后,您可以访问应用程序应用程序中的路径中的任何位置对象,您可以使用:

Then, anywhere in your routes that you have access to the app object, you can get it with:

let io = app.get("io");






以下是使用中间件设置 io 对象到每个 req 对象上,以便所有路线都可以使用。


Here's an example of using a middleware to set the io object onto every req object so it's available from all routes.

let server = app.listen(3000);
let io = require('socket.io')(server);

// place this middleware before any other route definitions
// makes io available as req.io in all request handlers
app.use(function(req, res, next) {
    req.io = io;
    next();
});

// then in any express route handler, you can use req.io.emit(...)






以下是使用不带中间件的模块构造函数的参数的示例:


Here's an example of using an argument to the module constructor without middleware:

// in mysocket.js
module.exports = (io) => {
    console.log('IO: ', io);
    io.on('connect', socket => {
       // handle various socket connections here
    });

    // put any other code that wants to use the io variable
    // in here


};

然后,在您的主文件中:

Then, in your main file:

let server = app.listen(3000);
let io = require('socket.io')(server);

// initialize my socketio module and pass it the io instance
require('./mysocket.js')(io);

这篇关于在expressjs路由中使用socket.io而不是在main server.js文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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