I have created a simple chat app. I want to persist data so whenever I refresh it should show the previous chat also. Currently, I am using socket.io, reactjs and nodejs/express. When I refresh the page all chats are gone why so? I think my backend is not working in below code. Currently, only client side is working and not backend why so? What is wrong in server.js?
Code:
server.js:
const express = require('express');
const socket = require('socket.io');
const app = express();
server = app.listen(5000, function(){
console.log('server is running on port 5000')
});
io = socket(server);
io.on('connection', (socket) => {
console.log(socket.id);
socket.on('SEND_MESSAGE', function(data){
io.emit('RECEIVE_MESSAGE', data);
})
});
chat.js:
import React, { Component } from 'react'
import './chat.css'
import Icon, {
Ionicons,
} from 'react-web-vector-icons'
import io from "socket.io-client";
export default class Chat extends Component {
constructor(props){
super(props);
this.state = {
message: '',
messages: []
};
this.socket = io('localhost:5000');
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', {
message: this.state.message
})
this.setState({message: ''});
}
}
render() {
return (
<div>
<div id="status"></div>
<div id="chat">
<div className="card">
<div id="messages" className="card-block">
{this.state.messages.map(message => {
return (
<div className="msgCard">{message.message}</div>
)
})}
</div>
</div>
<div className="row">
<div className="column">
<input id="inputmsg" type="text" placeholder="Enter Message...."
value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
</div>
<div className="column2">
<button id="send" className="button" onClick={this.sendMessage}>Send</button>
</div>
</div>
</div>
</div>
)
}
}
Note: backend is working on port 5000 and client on 3000 using concurrently.
When I go to port 5000 I am getting error 404 why so?
Screenshot:
Chat app:

