2016-06-21 5 views
1

Я пытался изучить node.js и socket.io и завершил пример с http://socket.io/get-started/chat/. Я добавил некоторые дополнительные функции и работает на localhost. Теперь я пытаюсь развернуть это на сервере на героку, но я не могу заставить его работать.socket.io chat example heroku

У меня недостаточно репутации, чтобы показать основные вещи, которые я прочитал. Я просмотрел статьи о героике «Начало работы с Heroku с помощью Node.js», «Развертывание приложений Node.js на Heroku» и «Использование WebSockets на Heroku с Node.js», но я все еще не могу понять, что делать.

HTML-страница показывает на мое приложение, но чат не работает: https://salty-ridge-74778.herokuapp.com/

Вот то, что я до сих пор:

index.html

<!doctype html> 
<html> 
    <head> 
    <title>Socket.IO chat</title> 
    <style> 
     * { margin: 0; padding: 0; box-sizing: border-box; } 
     body { font: 13px Helvetica, Arial; } 
     form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } 
     form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } 
     form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } 
     #messages { list-style-type: none; margin: 0; padding: 0; } 
     #messages li { padding: 5px 10px; } 
     #messages li:nth-child(odd) { background: #eee; } 
    </style> 
    </head> 
    <body> 
    <ul id="messages"></ul> 
    <form action=""> 
     <input id="m" autocomplete="off" /><button>Send</button> 
    </form> 
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> 
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script> 
    <script> 
     var socket = io(); 
     $('form').submit(function(){ 
     socket.emit('chat message', $('#m').val()); 
     $('#m').val(''); 
     return false; 
     }); 
     socket.on('chat message', function(msg){ 
     $('#messages').append($('<li>').text(msg)); 
     }); 
     socket.on('user connected', function(name){ 
     $('#messages').append($('<li>').text(name + " connected")); 
     }); 
    </script> 
    </body> 
</html> 

индекс .js

var app = require('express')(); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 

var nextUserId = 0; 
var users = []; 

app.set('port', (process.env.PORT || 5000)); 

app.get('/', function(req, res){ 
    res.sendFile(__dirname + '/index.html'); 
}); 

io.on('connection', function (socket) { 
    var socketId = socket.id; 
    users.push({ 'id': socketId, 'name': "User" + nextUserId }); 
    nextUserId++; 

    console.log(users[users.length - 1].name + ' joined with id ' + users[users.length - 1].id); 
    io.emit('user connected', users[users.length - 1].name); 
    socket.on('disconnect', function() { 
     console.log('user disconnected'); 
    }); 
    socket.on('chat message', function (msg) { 
     var name; 
     for (var x = 0; x < users.length; x++) { 
      if (users[x].id == socket.id) { 
       name = users[x].name; 
      } 
     } 

     io.emit('chat message', name + ": " + msg); 
     console.log('message: ' + name + ": " + msg); 
    }); 
}); 

http.listen(app.get('port'), function(){ 
    console.log('listening on port ' + app.get('port')); 
}); 

package.json

{ 
    "name": "socket-chat-example", 
    "version": "0.0.1", 
    "description": "my first socket.io app", 
    "dependencies": { 
    "express": "^4.10.2", 
    "socket.io": "^1.4.6" 
    }, 
    "engines": { 
    "node": "6.2.2" 
    } 
} 

PROCFILE

web: node index.js 

.gitignore

node_modules/ 

Чтобы установить приложение до Я напечатал эти команды в командной строке, как только я был в правильной складке er:

git init 
heroku create 
git add . 
git commit -m '1' 
heroku git:remote -a salty-ridge-74778 
git push heroku master 

Если бы кто-нибудь мог помочь, я был бы всегда благодарен.

ответ

2

Консоль показывает ошибки JavaScript, которые приводят к сбою вашего приложения. Откройте консоль отладки в вашем браузере:

Mixed Content: The page at ' https://salty-ridge-74778.herokuapp.com/ ' was loaded over HTTPS, but requested an insecure script ' http://code.jquery.com/jquery-1.11.1.js '. This request has been blocked; the content must be served over HTTPS. salty-ridge-74778.herokuapp.com/:25 Uncaught ReferenceError: $ is not defined

Вместо того, в том числе сценариев, как это, где вы жёстко их протокол для обеспечения или небезопасным:

<script src="http://code.jquery.com/jquery-1.11.1.js"></script> 

Включать их, как это, так что они наследуют протокол страница хостинга:

<script src="//code.jquery.com/jquery-1.11.1.js"></script> 
Смежные вопросы