Code (Backend)

Below is the Code for Creating above page:

server.js




// server.js
 
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
 
const ChatMessage = require("./models/ChatMessage");
 
const app = express();
const PORT = process.env.PORT || 5000;
 
// Middleware
app.use(cors());
app.use(express.json());
 
// MongoDB Connection
mongoose.connect("Your MongoDB connection string", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
 
// Routes
app.get("/messages", async (req, res) => {
    try {
        const messages = await ChatMessage.find();
        res.json(messages);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: "Internal Server Error" });
    }
});
 
app.post("/messages", async (req, res) => {
    try {
        const { user, message } = req.body;
 
        if (!user || !message) {
            return res
                .status(400)
                .json({ error: "User and message are required" });
        }
 
        const chatMessage = new ChatMessage({
            user,
            message,
        });
 
        await chatMessage.save();
 
        res.status(201).json(chatMessage);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: "Internal Server Error" });
    }
});
 
// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


ChatMessage.js




// models/ChatMessage.js
 
const mongoose = require('mongoose');
 
const chatMessageSchema = new mongoose.Schema({
    user: { type: String, required: true },
    message: { type: String, required: true },
    timestamp: { type: Date, default: Date.now },
});
 
const ChatMessage = mongoose.model('ChatMessage', chatMessageSchema);
 
module.exports = ChatMessage;


Step 3: To start the server run the following command.

node server.js

Step 4: Creating the frontend of the app by using the following command

cd ..
npx create-react-app chat-frontend
cd chat-frontend

Step 5: Install the required dependencies.

npm install axios react-router-dom socket.io-client

Folder Structure(Frontend):

Folder Structure (Frontend)

Dependencies(Frontend):

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.21.1",
"react-scripts": "5.0.1",
"socket.io-client": "^4.7.3",
"styled-components": "^6.1.8",
"web-vitals": "^2.1.4"
}

Example: Create the required files and add the following code.

App.css




/* src/App.css */
 
body {
    margin: 0;
    padding: 0;
    font-family: 'Arial', sans-serif;
    background-color: #cadcfc;
    color: #00246b;
}
 
.App {
    text-align: center;
}
 
h1 {
    color: #00246b;
}
 
ul {
    list-style-type: none;
    padding: 0;
}
 
li {
    background-color: #8ab6f9;
    margin: 5px;
    padding: 10px;
    border-radius: 5px;
}
 
input {
    padding: 10px;
    margin-right: 10px;
    border: 1px solid #00246b;
    border-radius: 5px;
}
 
button {
    padding: 10px;
    background-color: #00246b;
    color: #cadcfc;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
 
button:hover {
    background-color: #8ab6f9;
    color: #00246b;
}


ChatRoom.js




// ChatRoom.js
 
import React, { useState, useEffect } from 'react';
 
const ChatRoom = () => {
    const [messages, setMessages] = useState([]);
    const [user, setUser] = useState('');
    const [message, setMessage] = useState('');
 
    const fetchMessages = async () => {
        try {
            const response = await fetch('http://localhost:5000/messages');
            const data = await response.json();
            setMessages(data);
        } catch (error) {
            console.error('Error fetching messages:', error);
        }
    };
 
    const sendMessage = async () => {
        try {
            await fetch('http://localhost:5000/messages', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ user, message }),
            });
 
            // Clear the message input after sending
            setMessage('');
            // Fetch messages to update the list
            fetchMessages();
        } catch (error) {
            console.error('Error sending message:', error);
        }
    };
 
    useEffect(() => {
        // Fetch messages on component mount
        fetchMessages();
        // Poll for new messages every 2 seconds
        const interval = setInterval(() => {
            fetchMessages();
        }, 2000);
 
        return () => clearInterval(interval);
    }, []); // Run only once on mount
 
    return (
        <div>
            <h2>Chat Room</h2>
            <ul>
                {messages.map((message) => (
                    <li key={message._id}>
                        <strong>{message.user}:</strong> {message.message}
                    </li>
                ))}
            </ul>
            <div>
                <input
                    type="text"
                    placeholder="Your name"
                    value={user}
                    onChange={(e) => setUser(e.target.value)}
                />
                <input
                    type="text"
                    placeholder="Type your message..."
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                />
                <button onClick={sendMessage}>Send</button>
            </div>
        </div>
    );
};
 
export default ChatRoom;


App.js




//App.js
 
import './App.css';
import ChatRoom from './ChatRoom';
 
function App() {
    return (
        <div className="App">
            <ChatRoom />
        </div>
    );
}
 
export default App;


Step 6: To start the frontend run the following command.

npm start

Output:

Output of Online Chat Application

Online Chat Application Project in Software Development

Online chat application is one of the most common software development projects to date. In this article, we are going to make the Online chat application software development project from scratch, college students. We will be covering all the steps you have to do while developing this project.

Similar Reads

How to create a Online Chat Application?

Table of Content How to create a Online Chat Application? Step 1- Team Formation Phase: Creating a Dynamic Team Step 2- Topic Selection Step 3- Project Synopsys for Online Chat Application Step 4- Requirement Gathering (Creating SRS for Online Chat Application) Software Requirement Specification (SRS) Document | Online Chat Application 4.1 SRS (Online Chat Application) | Introduction: 4.2 SRS (Online Chat Application) | Overall Description: 4.3 SRS | Use case Diagram for Online Chat Application: ER Model of Online Chat Application: Data Flow Diagram of Online Chat Application: 5. Coding or Implementation of Online Chat Application Prerequisites: Approach to create Chat Application: Steps to Create the Project: Code (Backend): Step 6: Testing of Online Chat Application Step 7- Creating Project Presentation on Online Chat Application Generator Project Step 8- Writing a Research Paper on Library Management System: 8 Free Chat Apps to Message on Your Phone or Computer Future Enhancements for Online Chat Application:...

Step 1- Team Formation Phase: Creating a Dynamic Team

Team formation for a final-year project is a crucial aspect that can significantly impact the success and efficiency of the project. In the final year, students often have diverse academic backgrounds, skills, and interests. Therefore, forming a well-balanced team becomes essential to leverage the strengths of each member and address any potential weaknesses....

Step 2- Topic Selection

While making our project of Online Chat Application this will be our second step in which we will find an interesting problem statement and try to generate an idea to solve that problem using our knowledge....

Step 3- Project Synopsys for Online Chat Application

A project synopsis serves as a concise overview or summary of a proposed project, offering a brief but comprehensive insight into its objectives, scope, methodology, and expected outcomes. It typically acts as a preliminary document, providing supervisors, or evaluators with a quick understanding of the project before they delve into more detailed documentation....

Step 4- Requirement Gathering (Creating SRS for Online Chat Application)

This is the next phase after the submission of the synopsis report. We can do this process before the Synopsys report creation as well , It is all depends upon the project and their requirements. Here after getting an overview about the project now we can easily do the requirement gathering for our project....

Software Requirement Specification (SRS) Document | Online Chat Application

Below are some of the key points in a Software Requirement Specification Document:...

4.1 SRS (Online Chat Application) | Introduction:

The primary objective of this Software Requirements Specification (SRS) document is to outline the functional and non-functional requirements of the Online Chat Application project. The document provides a comprehensive description of the features and capabilities expected by the client....

4.2 SRS (Online Chat Application) | Overall Description:

4.2.1 Product Perspective:...

4.3 SRS | Use case Diagram for Online Chat Application:

A use case diagram for an online chat application illustrates the various interactions between users and the system. Here’s a simplified example of a use case diagram for an online chat application:...

ER Model of Online Chat Application:

An Entity-Relationship (ER) model for an online chat application typically identifies the main entities involved in the system and their relationships. Here’s a simplified ER model for an online chat application:...

Data Flow Diagram of Online Chat Application:

A Data Flow Diagram (DFD) for an online chat application illustrates the flow of data within the system, including how data moves between processes, entities, and data stores. Here’s a simplified DFD for an online chat application:...

5. Coding or Implementation of Online Chat Application

At this stage, the fundamental development of the product starts. For this, developers use a specific programming code as per the design. Hence, it is important for the coders to follow the protocols set by the association. Conventional programming tools like compilers, interpreters, debuggers, etc. are also put into use at this stage....

Prerequisites:

MongoDB Express.js React.js Node.js MERN Stack...

Approach to create Chat Application:

First, We will create a backend server which will serve a middleman between mongDB and React FrontEnd. We will create an Interactive and Simple UI design for the frontEnd in which the message is sent and the other user responds to it. All the messages along with userName will be sent to backend using above created backend. We will use Socket.IO toupport real time chat. Lastly, we will create a database in MongoDB to store the messages....

Steps to Create the Project:

Step 1: Create a new project folder and navigate to it:...

Code (Backend):

Below is the Code for Creating above page:...

Step 6: Testing of Online Chat Application

...

Step 7- Creating Project Presentation on Online Chat Application Generator Project

...

Step 8- Writing a Research Paper on Library Management System:

...

8 Free Chat Apps to Message on Your Phone or Computer

...

Future Enhancements for Online Chat Application:

...

Contact Us