Giter VIP home page Giter VIP logo

adrianhajdin / project_chat_application Goto Github PK

View Code? Open in Web Editor NEW
3.9K 3.9K 1.5K 465 KB

This is a code repository for the corresponding YouTube video. In this tutorial we are going to build and deploy a real time chat application. Covered topics: React.js, Node.js, Express.js, and Socket.io.

Home Page: https://www.jsmastery.pro

JavaScript 70.42% HTML 3.60% CSS 25.85% Procfile 0.12%
react react-hooks react-project reactjs

project_chat_application's Introduction

Realtime Chat Application

Chat Application

Introduction

This is a code repository for the corresponding video tutorial.

In this video, we will create a full Realtime Chat Application. We're going to use React on the front end, with NodeJS + Socket.io web socket library on the back end.

By the end of this video, you will have a strong understanding of how to send and receive messages using web sockets and Socket.io to make any real-time application.

Launch your development career with project-based coaching - https://www.jsmastery.pro

Setup:

  • run npm i && npm start for both client and server side to start the development server

project_chat_application's People

Contributors

adrianhajdin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

project_chat_application's Issues

nodemon not working

On server folder, the "start" script is:
image

but you don't have nodemon on your dependencies
image

Install nodemon as dev dependency with -D flag and change scripts to this:
"scripts": { "start": "node index.js", "dev": "nodemon index.js" },

The Server Crashes on account of Duplicate user sending the message.

The code in Chat.js on client-side, sends an error when it finds a duplicate username, but that can be passed by pressing ok, as it is an alert, see code for reference

socket.emit('join', {name, room}, (error) => {
if(error){
alert(error);
}
});
}, [ENDPOINT, location.search]);

Now on the server-side, a duplicate user has no properties like user.name or user.room so that remains undefined.
Solution: By not letting the duplicate user enter into the room, it will also be a potential solution to the problem:

io.to(user.room).emit('message', {user: user.name, text: message});
^

TypeError: Cannot read property 'room' of undefined.

Can't run npm start correctly for client on windows 10.

This is the console message.I use windows10.I try to google for this but still not work. Coule you help me fix this? Thanks!

E:\project_chat_application-master\client>npm i

> [email protected] postinstall E:\project_chat_application-master\client\node_modules\babel-runtime\node_modules\core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!  

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
> https://opencollective.com/core-js 
> https://www.patreon.com/zloirock 

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)


> [email protected] postinstall E:\project_chat_application-master\client\node_modules\core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!  

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js 
> https://www.patreon.com/zloirock 

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\chokidar\node_modules\fsevents):     
Starting the development server...

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: spawn cmd ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)      
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)   
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\13AB005\AppData\Roaming\npm-cache\_logs\2019-10-03T10_17_30_350Z-debug.log

Comment to easier

Can you comment each line at files: Chat.js, Users.js, InfoBar.js, server/index.js ?
I'm a student and newbie ! I can't understand that files. I hope You will response to me, soon!
Thanks!

TypeError: Cannot read properties of undefined (reading 'room')

I am getting this issue in my code.
Can anybody help me?

Issue:

Server has started on port 5001
{ id: 'Qg9lzlaYKvZL8It5AAAB', name: 'Jatan', room: 'Test' }
C:\Users\Jatan\chat-app\server\index.js:46
        io.to(user.room).emit('message', {user:user.name, text: message})
                   ^

TypeError: Cannot read properties of undefined (reading 'room')
    at Socket.<anonymous> (C:\Users\Jatan\chat-app\server\index.js:46:20)
    at Socket.emit (node:events:520:28)
    at Socket.emitUntyped (C:\Users\Jatan\chat-app\server\node_modules\socket.io\dist\typed-events.js:69:22)
    at C:\Users\Jatan\chat-app\server\node_modules\socket.io\dist\socket.js:465:39
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
[nodemon] app crashed - waiting for file changes before starting...

My server-side index.js :

const express = require('express')
//const socketio = require('socket.io')
//const http = require('http')

const {createServer} = require('http')
const {Server} = require('socket.io')

const { addUser, removeUser, getUser, getUsersInRoom} = require('./users')

const PORT = process.env.PORT || 5001

const router = require('./router')


// Basic code to start socket.io server
const app = express()
//const server = http.createServer(app)
const httpServer = createServer()
const io = new Server(httpServer, {
    cors: {
        origin: "http://localhost:3005"
      }
})

io.on('connection', (socket) => {

    socket.on('join', ( {name, room}, callback ) => {
        const {error, user} = addUser({ id: socket.id, name, room})

        console.log(user)
        if(error) return callback(error);

        socket.emit('message', {user: 'admin', text: `${user.name}, welcome to the room ${user.room}`})
        socket.broadcast.to(user.room).emit('message', {user: 'admin', text:`${user.name}, has joined!`})

        socket.join(user.room)

        io.to(user.room).emit('roomData', {room: user.room, users: getUsersInRoom(user.room)})
        
        callback();
    })

    socket.on('sendMessage', (message , callback) => {
        const user = getUser(socket.id)

        io.to(user.room).emit('message', {user:user.name, text: message})

        callback();
    })

    socket.on('disconnect', () =>{
        const user = removeUser(socket.id)

        if(user) {
            io.to(user.room).emit('message', { user: 'Admin', text: `${user.name} has left.` });
            io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room)});
          }
    })
});

app.use(router)

httpServer.listen(PORT, () => console.log(`Server has started on port ${PORT}`))

users.js:

const users = [];

const addUser = ({id,name,room}) => {
    //name = name.trim().toLowerCase();
    //room = room.trim().toLowerCase();

    const existingUser = users.find((user)=> user.name === name && user.room === room)

    if (existingUser) {
        return {error: 'Username is taken'}
    }

    const user = {id,name,room};

    users.push(user);

    return {user}
}

const removeUser = (id) => {
    const index = users.findIndex((user) => user.id === id)

    if (index !== -1){
        return users.splice(index, 1)[0]
    }
}

const getUser = (id) => {users.find((user) => user.id === id)}

const getUsersInRoom = (room) => {users.filter((user) => user.room === room)}

module.exports = { addUser, removeUser, getUser, getUsersInRoom}

TypeError: Cannot read property 'room' of undefined

io.to(user.room).emit('message', {user:user.name, text:message});
^

TypeError: Cannot read property 'room' of undefined
at Socket. (D:\React.js\Chat App\server\index.js:28:20)
at Socket.emit (events.js:210:5)
at D:\React.js\Chat App\server\node_modules\socket.io\lib\socket.js:528:12
at processTicksAndRejections (internal/process/task_queues.js:75:11)
[nodemon] app crashed - waiting for file changes before starting...

CORS error

The app stops working in the production environment. The console states,"No Access-Control-Allow-Origin".

Send Images

How can I send Images to other people?

import React, { useState, useEffect } from "react";
import queryString from 'query-string';
import io from "socket.io-client";

import TextContainer from '../TextContainer/TextContainer';
import Messages from '../Messages/Messages';
import InfoBar from '../InfoBar/InfoBar';
import Input from '../Input/Input';

import './Chat.css';

const ENDPOINT = 'localhost:5000';

let socket;

const Chat = ({ location }) => {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const [users, setUsers] = useState('');
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const [file, setFile] = useState('');

useEffect(() => {
const { name, room } = queryString.parse(location.search);

socket = io(ENDPOINT);

setRoom(room);
setName(name)

socket.emit('join', { name, room }, (error) => {
  if(error) {
    alert(error);
  }
});

}, [ENDPOINT, location.search]);

useEffect(() => {
socket.on('message', message => {
setMessages(messages => [ ...messages, message ]);
});

socket.on('file', file => {
  setFile(messages => [ ...messages, file ]);
});

socket.on("roomData", ({ users }) => {
  setUsers(users);
});

}, []);

const sendMessage = (event) => {
event.preventDefault();

if(message) {
  socket.emit('sendMessage', message, () => setMessage(''));
}
if(file) {
  console.log(file)
  socket.emit('sendMessage', file, () => setFile(''));
}

}

function selectFile(e) {
setMessage(e.target.files[0].name);
setFile(e.target.files[0]);
}

return (










);
}

export default Chat;

This is the code that I've modified.

sendMessage function not working

When I click on send button, nothing happens. sendMessage method is not working neither I am getting messages from admin. Is it an issue of socket.io ?

how to deploy

I saw the youtube video and did the same deployment. But the back end is not working, like the application is not working it says. I deployed it in Heroku and the front end in Netlify. But still, I end up in the CORS issue. Can you please guide me?

Could you add a license to the project?

Hi Adrian,

many thanks for your work. However, could you add a license to this project?

That would be helpful, because I would like to work with your project, but without the license I am not allowed to do so.

Many thanks for your help in advance!

Open causing the problem on the server side

I have detected a security vulnerability. When a warning is received from the

if(!name || !room) return { error: 'Username and room are required.' };
line, the person who wants to join the chat can see the path without changing the name of the chat. It hurts. If is added to the line after this line document.location="/", the problem is eliminated.

Name Capitalization

The name on the chatroom is not as displayed as the user writes it. Example, "Dylan" appears as "dylan"

HELP

Hi,

i really need help with sockets. so what i have is allconversations screen which has all the conversations on and the chat screen which is the actually chat itself. i have successfully implemented sockets that when both users are inside the chat messages get sent live. my problem is if user 1 is on allconversations screen and user 2 is inside chat and user2 sends user 1 a message. the message gets rendered live for user 2 but user 1 does not know about this new message because he/she are not inside chat. how to implement a feature for user 1 that if this scenario happens the conversation that receives a new messages becomes bold on the allconversations screen?

thank you in advance, i have been trying to solve this for a month now and couldnt get anywhere :(

Error with command: npm i

PS C:\Users\p-c\Downloads\Github\project_chat_application> npm i
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\p-c\Downloads\Github\project_chat_application/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\p-c\Downloads\Github\project_chat_application\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\p-c\AppData\Local\npm-cache_logs\2022-05-27T13_06_02_996Z-debug-0.log

Create an "About Us" page

There is little information on the chatroom page that describes the details of this project. There should be a separate "about us" page that gives credit to the creator and gives more information about the repository.

live site issue

Screenshot (322)
The server is working fine and there's no error showing but still messages are not sending. it's working fine on localhost though

TypeError: callback is not a function

io.on('connection', (socket) => {
socket.on('join', ({name, room}, callback) => {
const {error, user} = addUser({id: socket.id, name, room});

        if(error) return callback(error);
        socket.join(user.room);

        socket.emit('message', {user: 'admin', text:`${user.name}, welcome to the room ${user.room}`});
        // sends a message to every user besides ourselves
        socket.broadcast.to(user.room).emit('message', {user:'admin', text:`${user.name} has joined`});


        callback();
});

Multiple users with same name in the same room

clients -> src -> components -> join -> join.js

line: <Link onClick={event => (!name || !room) ? event.preventDefault() : null} to={/chat?name=${name}&room=${room}}>

Can you recommend a method to check whether the user name is present in the same room or not, if present then redirect it to the home page with an alert "Enter another name for the room" or assign a different name to the same user?
The thing is if two users with the same name are joining the same room then the app gets crashed.

CSS multi class error

In the message box, the styling for justifyEnd justifyStart which are declared as the second className doesnt work.. I cant solve this. can anyone help??
error

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.