Я разработал приложение для чата в node.js, используя socket.io и express. На моем локальном хосте все работает отлично, но мне нужно разместить его, чтобы я узнал о Heroku.
Когда я отправляю сообщение и пытаюсь запустить его, оно работает только с первым пользователем, но при подключении другого пользователя происходит сбой. Когда я вижу свои журналы, я получаю эту ошибку несколько раз:
2020-01-10T00:33:28.605853+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/socket.io/?EIO=3&transport=polling&t=M-CtiWS" host=chatescuela.herokuapp.com request_id=a22e2212-fad1-4158-a1b8-7ab15c15a1d8 fwd="(here goes my ip)" dyno= connect= service= status=503 bytes= protocol=https
Это мой код: Сервер
const app = express();
const path = require('path');
//settings
app.set('port', process.env.PORT || 3000);
//static files
app.use(express.static(path.join(__dirname, 'public')));
//start server
const server = app.listen(app.get('port'), () => {
console.log('Server on port', app.get('port'));
});
//crea el puerto
const socket = require('socket.io')
const io = socket(server)
const users = {}
console.log("-------Server's up and running!-------")
//when each user connects, the user is now 'socket'
io.on('connection', socket => {
var userst = io.engine.clientsCount
socket.emit('users', userst)
//when it connects, it sends "chat-message" and the value hello world
socket.on('new-user', name => {
users[socket.id] = name
socket.broadcast.emit('user-connected', name)
//IP
var request = require('request');
request({
method: 'GET',
url: 'https://api.ipdata.co/?api-key=0a2d88f367cd4a9a3639413ca2b3cf5fc2f6ec0b57fe3b87849e4922&fields=ip,country_name',
headers: {
'Accept': 'application/json'
}}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log(`${name} se ha unido bajo la IP:`, body);
console.log("----------------")
if(error){
console.log(`Error: ${error}`)
}
});
})
//in script.js, when it sends a message the server
//receives it as message parameter
socket.on('send-chat-message', message => {
//sends the message to everyone EXCEPT the author
socket.broadcast.emit('chat-message', { message: message, name: users[socket.id] })
})
socket.on('typing', name => {
socket.broadcast.emit('typing', name)
})
socket.on('stopped-typing', stoppedname => {
socket.broadcast.emit('has-stopped', stoppedname)
})
socket.on('disconnect', () => {
socket.broadcast.emit('user-disconnected', users[socket.id])
delete users[socket.id]
})
})
Пользователи
const name = prompt("Ingresa tu nombre:")
const socket = io()
const messageForm = document.getElementById("send-container")
const messageContainer = document.getElementById("message-container")
const messageInput = document.getElementById("message-input")
const photo = document.getElementById("photo")
const arrow = document.getElementById("arrow")
const sendButton = document.getElementById("send-button")
const audio = document.getElementById("audio")
var messageElementType
var passed
var counter = 1
arrow.addEventListener('click', () => {
return location.reload()
})
console.log("---------------------")
console.log("---Coded by NathanO--")
console.log("---------------------")
console.warn("Prohibida la reproducción parcial o total de éste producto")
if(name == null || name == undefined || name == ""){
passed = false
error()
} else {
passed = true
}
function error(){
alert("Error: El nombre debe de contener caracteres.")
arrow.style.display = "block"
sendButton.innerText = "Error"
sendButton.addEventListener('click', function(){
alert("Necesitas ingresar tu nombre")
})
return passed = false
}
if(passed == true){
sendButton.innerText = `Enviar como ${name}`
appendMessageM(`Te has unido como: ${name}`)
socket.emit('new-user', name)
}
if(passed == true){
socket.on('users', userst => {
const messageElement = document.createElement('div')
if(userst >= 3){
messageElement.innerText = `Hay otros ${userst - 1} usuarios conectados`
} else if(userst == 2){
messageElement.innerText = `Hay otro usuario conectado`
} else if(userst == 1){
messageElement.innerText = `No hay ningún otro usuario conectado`
}
messageElement.style.background = "rgb(61, 197, 197)"
messageElement.style.color = "white"
messageContainer.append(messageElement)
})
}
//it receives chat message from server and "data" is the hello world
socket.on('chat-message', data => {
appendMessageO(`${data.name}: ${data.message}`)
photo.style.display = "block"
setTimeout(function(){
photo.style.display = "none"
}, 3000)
audio.play()
//restart the note if necessary
audio.currentTime = 0
})
socket.on('user-connected', name => {
appendMessageM(`${name} se ha unido`)
})
socket.on('user-disconnected', name => {
appendMessageM(`${name} se ha ido`)
})
if(passed == true){
messageForm.addEventListener('keypress', () => {
socket.emit('typing', name)
const message = messageInput.value
if(message.length < 1){
socket.emit('stopped-typing', name)
}
})
}
socket.on('has-stopped', stname => {
const typingId = document.getElementById("typeid");
document.getElementById("message-container").removeChild(typingId);
counter = 1
})
if(passed == true){
socket.on('typing', username => {
if(counter == 1){
messageElementType = document.createElement('div')
messageElementType.innerText = `${username} está escribiendo...`
messageElementType.style.background = "rgb(78, 170, 170)"
messageElementType.style.color = "white"
messageElementType.setAttribute('id', 'typeid');
messageContainer.append(messageElementType)
}
counter = 2
socket.on('chat-message', data => {
const typingId = document.getElementById("typeid");
document.getElementById("message-container").removeChild(typingId);
counter = 1
})
})
} else {
console.log("Error: No ingresó nombre de usuario")
}
if(passed == true){
messageForm.addEventListener('submit', e => {
e.preventDefault()
const message = messageInput.value
//it sends the signal send chat message and sends const message
//as the parameter
if(message.length < 1){
return alert("¡Tu mensaje debe contener texto!")
} else if(message.length > 630){
return alert("Tu mensaje no puede tener más de 630 caracteres. Actualmente tienes "+message.length+" caracteres.")
}
appendMessageA(`Tú: ${message}`)
photo.style.display = "block"
messageInput.value = ""
setTimeout(function(){
photo.style.display = "none"
}, 4000)
if(message == 'Ping'){
appendMessageM(`Pong, ${name}`)
socket.emit('stopped-typing', name)
} else {
socket.emit('send-chat-message', message)
}
})
}
// messageForm.addEventListener('keypress', () => {
// socket.emit('typing', name)
// })
// socket.on('typing', datos => {
// appendMessage(`${name} is typing...`)
// // })
function appendMessageA(message){
const messageElement = document.createElement('div')
messageElement.style.background = "rgb(38, 95, 117)"
messageElement.innerText = message
messageElement.style.color = "white"
messageContainer.append(messageElement)
}
function appendMessageO(message){
const messageElement = document.createElement('div')
messageElement.innerText = message
messageElement.style.background = "rgb(21, 149, 172)"
messageContainer.append(messageElement)
}
function appendMessageM(message){
const messageElement = document.createElement('div')
messageElement.innerText = message
messageElement.style.background = "rgb(152, 207, 207)"
messageElement.style.color = "white"
messageContainer.append(messageElement)
}
Может кто-нибудь помочь мне, как исправить эту ошибку?