socket.io没有在heroku上加载

时间:2017-09-17 11:46:51

标签: node.js heroku socket.io

我正在使用node.js,express,socket.io,mongodb,mongoose,mongolab和heroku来构建简单的聊天。

在localhost(没有heroku)上一切都很好用,但是当我在heroku上部署我的app时,socket.io.js没有加载。

https://prnt.sc/gm6fz0

我已经阅读了大约10-20个其他类似问题并尝试了其他变体,但socket.io.js仍然无法加载。

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 = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var mongoose = require('mongoose');
var mongodb = require('mongodb');

server.listen(8080);

var uri = 'mongodb://username:password@ds141264.mlab.com:41264/chat';

var index = require('./routes/index');
var users = require('./routes/users');

mongoose.connect(uri, function(err){
  if(err) {
    console.log(err);
  } else {
    console.log('connected to mongo db');
  }
});

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function callback () {

  var chatSchema = mongoose.Schema ({
    msg: String,
    created: {type: String, default: function(){return new Date()}}
  });

  var Chat = mongoose.model('Message', chatSchema);

  io.on('connection', function(socket){
    console.log('a user connected');
    var query = Chat.find({});
    query.sort({'_id': -1}).limit(10).exec(function(err, docs){
      if (err) throw err;
      console.log('sending old msgs');
      socket.emit('load old msgs', docs);
    });

    socket.on('disconnect', function(){
      console.log('user disconnected');
    });
    socket.on('chat', function(msg){
      console.log('message: ' + msg);
      var newMsg = new Chat({ msg: msg });
      newMsg.save(function(err){
        if(err) throw err;
        io.emit('chat', msg);
      });
    });
  });
});


app.use(express.static(__dirname + '/public'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//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('/', index);
app.use('/users', users);

// 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;

global.js - 客户端

var socket = io.connect();

$('#send-message-btn').click(function () {
    var msg = $('#message-box').val();
    socket.emit('chat', msg);
    $('#message-box').val('');
    return false;
});

socket.on('chat', function (msg) {
  var dadd = new Date;
  $('#messages').append($('<time>').text(dadd));
  $('#messages').append($('<p>').text(msg));
});


socket.on('load old msgs', function(docs){
  for(var i=0; i < docs.length; i++) {
    $('#messages').prepend($('<p>').text(docs[i].msg));
    $('#messages').prepend($('<time>').text(docs[i].created));
  }
});

1 个答案:

答案 0 :(得分:0)

根据heroku提供的文档(使用Socket.io的应用程序应启用会话亲和性。如果您计划使用节点的群集模块或将应用程序扩展为多个dynos,您还应该遵循Socket.io的多个 - 节点说明。),您基本上必须从项目目录执行以下命令。

heroku features:enable http-session-affinity

最佳,

Daksh Miglani