Socet.io不在路线上工作

时间:2017-12-01 01:00:53

标签: node.js express socket.io pug

我已经搜索了所有,但我找到的只是使用socket.io的基本方法。 我试图在我的一条路线中使用socket.io但是不能。我正在使用express,node.js和jade。我的问题是我无法在其他路线中访问io变量表单app.j.我不确定我是否应该每次都打电话给它。此外,当我尝试要求导出的app.js模块时,它说无法找到app.j.

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
//SOCKET/I/o
 var http = require('http').Server(app);
 var io = require('socket.io')(http);
 var port = process.env.PORT || 3000;
//
var login = require('./routes/login');
 var index = require('./routes/index');
var users = require('./routes/users');
var news = require('./routes/news');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
// TODO Not sure if this is working
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', login);
app.use('/index',index);
app.use('/users', users);
app.use('/news',news);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
 var err = new Error('Not Found');
 err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
 // set locals, only providing error in development
 res.locals.message = err.message;
 res.locals.error = req.app.get('env') === 'development' ? err : {};

 // render the error page
 res.status(err.status || 500);
 res.render('error');
 });
 module.exports = app;

/routes/login.js

  var express = require('express');
 var app = require('./app');
 var firebase = require("firebase");
 var router = express.Router();



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

});

io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
  console.log(data);
});
});
 module.exports = router;

/views/login.jade

doctype html
html    
head 
    title login
    link(rel='stylesheet', href='/stylesheets/main.css')

body
    input(type="email",placeholder="email",id="userEmail")
    input(type="password",placeholder="password",id="userPassword")
script(src="https://cdn.socket.io/socket.io-1.2.0.js")
script.
    socket.on('connection', function (data) {
        console.log(data);
        socket.emit('my other event', {my: 'data'});
    });
button(onclick='signin()') Sign In
button(onclick='signup()') Sign Up

1 个答案:

答案 0 :(得分:0)

由于您没有使用html-router运行单页面应用程序,因此Socket.io实例仅在第一条路线上初始化,因此对于每条路线,您必须执行此操作:

var socket = io()
socket.on('connection', function (data) {
    console.log(data);
    socket.emit('my other event', {my: 'data'});
});

只有这样才能奏效。