It deploys successfully and releases a successful build, but the socket.io module doesn't work for some reason. I've tried a variety of solutions that were posted on this forum but none seem to work for me. Oddly enough, it works fine on localhost but not on heroku, so I'm not sure what's up. Here's my code:
Server Side:
var express = require('express');
var socket = require('socket.io');
var app = express();
const PORT = process.env.PORT || 8080;
const server = app.listen(PORT, "0.0.0.0", function(){
console.log('server is running on port: ' + PORT);
});
io = socket(server);
io.on('connection', (socket) => {
console.log(socket.id);
socket.on('SEND_MESSAGE', function(data){
io.emit('RECEIVE_MESSAGE', data);
})
});
Client Side:
import React from "react";
import io from "socket.io-client";
class Chat extends React.Component{
constructor(props){
super(props);
this.state = {
username: '',
message: '',
messages: []
};
this.socket = io.connect('localhost:8080');
this.socket.on('RECEIVE_MESSAGE', function(data){
addMessage(data);
});
const addMessage = data => {
console.log(data);
this.setState({messages: [...this.state.messages, data]});
console.log(this.state.messages);
};
this.sendMessage = ev => {
ev.preventDefault();
this.socket.emit('SEND_MESSAGE', {
author: this.state.username,
message: this.state.message
})
this.setState({message: ''});
}
}
render(){
return (
<div className="container" style={{width: '100%', height: '100%'}}>
<div className="card" >
<div className="card-body">
<div className="card-title">Global Chat</div>
<hr/>
<div className="messages">
{this.state.messages.map(message => {
return (
<div>{message.author}: {message.message}</div>
)
})}
</div>
</div>
<div className="card-footer">
<input type="text" placeholder="Username" value={this.state.username} onChange={ev => this.setState({username: ev.target.value})} className="form-control"/>
<br/>
<input type="text" placeholder="Message" className="form-control" value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
<br/>
<button onClick={this.sendMessage} className="btn btn-primary form-control">Send</button>
</div>
</div>
</div>
);
}
}
export default Chat;
I know the url isn't supposed to be 'localhost:8080' and I've tried other options like putting in the url as the heroku url such as 'my-app.herokuapp.com' but it always gives some error, which I'm not sure of and all the solutions I saw on this forum didn't work. Any help would be appreciated! Thanks in advance!