简体   繁体   English

调用变量到在Node.js和Express中不起作用的其他路由

[英]Calling a variable to a different route not working in nodejs and express

I have my app.js set up like this: 我的app.js设置如下:

app.js app.js

  var express = require('express'); var socket_io = require("socket.io"); var app = express(); //Our route variables. var routes = require('./routes/index'); var users = require('./routes/users'); var work = require('./routes/work'); // Socket.io var io = socket_io(); app.io = io; var playground = require('./routes/playground')(io); //CODE I WANT MOVED TO playground.js! //Socket IO playground io.on('connection', function(socket) { console.log('a user connected'); socket.on('chat message', function(msg) { io.emit('chat message', { message: msg.message, nickname: msg.nickname }); }); socket.on('disconnect', function() { console.log('a user disconnected'); }); }); 

I was told I could send .io to my route playground.js like this: 有人告诉我,我可以.IO发送给我的路线playground.js是这样的:

var playground = require('./routes/playground')(io);

However I get the following error cannot call method of 'IndexOf' undefined 但是我收到以下错误,无法调用未定义'IndexOf'的方法

I do not want my socket.io code to be in app,js because I don't want app.js to become messy. 我不希望我的socket.io代码位于app.js中,因为我不希望app.js变得混乱。 (The code will grow overtime) I only want to use socket.io in playground.js because all of my test apps will be there. (代码将随着时间的推移而增长)我只想在Playground.js中使用socket.io,因为我所有的测试应用程序都在那里。 Please let me know if I can make this more clear 请让我知道是否可以更清楚地说明这一点

playground.js playground.js

 var express = require('express'); var router = express.Router(); module.exports = function(io) { io.on('connection', function(socket) { console.log("connection made!"); }); }; router.get('/', function(req, res, next) { res.render('playground'); }); module.exports = router; 

In your playground.js the last line module.exports = router; 在你playground.js最后一行module.exports = router; supersedes the previous module.exports declaration. 取代之前的module.exports声明。 Try: 尝试:

//routes/playground.js
var express = require('express');
var router = express.Router();


module.exports = function(app, io) {
  io.on('connection', function(socket) {
    console.log("connection made!");
  });
};

router.get('/', function(req, res, next) {
  res.render('playground');

app.use('/', router);
});

and try require('./routes/playground')(app, io); 并尝试require('./routes/playground')(app, io); in your app.s 在您的应用程序中

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

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