简体   繁体   English

无法app.get('foo')(Express / Node JS)

[英]cannot app.get('foo') (Express/Node JS)

I am currently working on adding a real-time chat into a particular website. 我目前正在为特定网站添加实时聊天。 I am using Express JS package and the initialization information (ie start/listen server, etc.) is located in 'www/bin' (by default). 我正在使用Express JS软件包,并且初始化信息(即启动/监听服务器等)位于“ www / bin”(默认情况下)中。

So, this is my init file (ie 'www/bin'): 因此,这是我的初始化文件(即“ www / bin”):

 /**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('nodeblog:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
  * Listen to Sockets
  */
var io = require('socket.io').listen(server);
app.set('socketio', io); // FIXME: Cannot app.get('socketio') w/out req


/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

And the thing is that I cannot 'get' this SocketIO declaration as I need in one of the router files to exchange messages between client/server. 事实是,我无法像在路由器文件之一中那样“获取”此SocketIO声明以在客户端/服务器之间交换消息。

Here is this route file: 这是此路由文件:

var express = require('express');
var router = express.Router();
var app = express();
// Models
var auth = require('../models/auth');

var io = app.get('socketio');

router.get('/', auth.ensureAuthenticated, function(req, res, next) {
  res.render('chat', {
    title: 'Chat'
  });
});

io.on('connection', function(socket){
  console.log('a user connected');

  socket.on('chat message', function(msg) {
    io.emit('chat message', msg);
  });

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

module.exports = router;

So, when I try to app.get('socketio)' it returns undefined 因此,当我尝试app.get('socketio)'时,它返回的是undefined

Do you know how do I need to correctly declare this app.get('socketio',io) so that I can access it anywhere (but not into the request methods) 您知道如何正确声明此app.get('socketio',io)以便可以在任何地方访问它(但不能访问请求方法)

Error: 错误:

chat.js:15
io.on('connection', function(socket){
  ^

TypeError: Cannot read property 'on' of undefined

Firstly, we need to separate our function (containing io.on('connection', ...) in a separate file. 首先,我们需要将函数(包含io.on('connection', ...)分开在单独的文件中。

Secondly, we need to add to the 'www/bin' so server can listen to it as well. 其次,我们需要添加到“ www / bin”,以便服务器也可以收听它。 Answer is if we change in 'www/bin': 答案是如果我们更改“ www / bin”:

var io = require('socket.io').listen(server);
require('../models/socketio.js')(io);

That's the answer. 那就是答案。

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

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