We all have seen the tutorials and article on how to create Chat Room in Node.js where multiple users can send and receive messages to each other. But in this article, I will explain how we can create Private Real Time chatting app. As the title suggests, here we will use AngularJs(version 1.6.5) as the front end framework. This is SPA application, which uses UI-bootstrap, so I expect from you to have a little familiarity with it. Server-side is written in Nodejs (version 8.9.3) and Mysql (version 5.7.21-log).
After completing this series of articles, If you want toreport an issue, you can use GitHub for that, I have uploaded thecode to the GitHub. Using GitHub will be very easy for all of us to track all the issues.
Prerequisites:
Once go through above articles if you are not familiar with those topics listed above and I assume reader of this article has the intermediate knowledge of Nodejs and AngularJs. In this application, we will implement below-listed features,
- Login and registration feature in order to make the user account.
- Checking a session when logged in.
- Creating online Chat list.
- Sending message to each user
But before going any further, let’s take a look at the final outcome of this article.
1. Homepage (Private chatting application)
2. Online chat list (Private chatting application)
As this article seems lengthy, I have divided it into3 parts. Each part of this article covers unique part in building the Private Real Time chatting app.
Part 1: Covers the Overview, Setting up the server, Setting the AngularJs application and entire Login page & Registration page operation.
Part 2: Covers the Homepage and Chat list implementation.
Part 3: Building Simple Real-time Chat Application.
1. Creating MySQL Database
Overall we are going to create 2 tables.
- user table: This table holds the information about users.
- message table: This table holds the messages associated with Conversation Id.
To create these tables, Open the PHPMyAdmin (if you are using XAMP/WAMP) which is located athttp://localhost/phpmyadminand execute these SQL queries, you can use PHPMyAdmin graphical interface to create tables if you are familiar with it.
SQL Queries:
CREATE DATABASE chat; USE chat; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(10) NOT NULL, `password` varchar(20) NOT NULL, `online` enum('N','Y') NOT NULL, `socketid` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; CREATE TABLE `message` ( `id` int(11) NOT NULL AUTO_INCREMENT, `from_user_id` varchar(45) DEFAULT NULL, `to_user_id` varchar(45) DEFAULT NULL, `message` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
2. Creating a new Nodejs project
1. Let’s start off by creating a new Nodejs project by usingng init
command.This command will create a new package.json file.
2. After that copy the dependencies from below package.json and paste it in your file and run npm install
.
Below is my package.json file for this application.
package.json:
{ "name": "private-chat-app-using-angularjs-nodejs-and-mongodb", "version": "1.0.0", "description": "This is a private chat application in angularjs and nodejs using Mysql as database.", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Shashank Tiwari", "license": "ISC", "dependencies": { "body-parser": "^1.18.2", "express": "^4.16.2", "mysql": "^2.15.0", "socket.io": "^2.0.4" }, "devDependencies": { "eslint": "^4.16.0" } }
3. Directory structure and Project overview
Till now, you have a package.json file and node_modules folder in your project. Let’s create create Project directories and files required to run the application. The below-shown image is replicating the directory structure and files created in this application.
=>In the project root, we have two parent directories/client
and /utils
and a server.js
file.
=> Insideserver.js
file, we will write code to set up the Nodejs server.
=> Inside, /client
directory there are 3 subdirectories/css
, js
and /views
, and the names of these directories self-explanatory.
=> So create all the files and directories and once you create all the files you can move to next heading and set up the AngularJs in your application.
=> You can skip READ.md
and download ui-bootstrap
from here.
4. Creating a Nodejs Server
At this point, we have all the directories and files created with us, Now we will create a Nodejs server, if you are a regular follower of this Blog then you must be familiar that, we always keep our server setup identical in each project, which ridiculously easy to set up.
=> Open the server.js
file and write down the below code into it.
=> In the below code we have included the application routes and socket events and did the setup of the application configuration.
/** * Real Time chatting app * @author Shashank Tiwari */'use strict'; const express = require("express"); const http = require('http'); const socketio = require('socket.io'); const bodyParser = require('body-parser'); const socketEvents = require('./utils/socket'); const routes = require('./utils/routes'); const config = require('./utils/config'); class Server{ constructor(){ this.port = process.env.PORT || 3000; this.host = `localhost`; this.app = express(); this.http = http.Server(this.app); this.socket = socketio(this.http); } appConfig(){ this.app.use( bodyParser.json() ); new config(this.app); } /* Including app Routes starts*/ includeRoutes(){ new routes(this.app).routesConfig(); new socketEvents(this.socket).socketConfig(); } /* Including app Routes ends*/ appExecute(){ this.appConfig(); this.includeRoutes(); this.http.listen(this.port, this.host, () => { console.log(`Listening on http://${this.host}:${this.port}`); }); } } const app = new Server(); app.appExecute();
5. Connecting to Database
Here we are using Mysql as the Database engine, we will use a node-mysql package to connect nodejs server to MySQL server.
=>Opendb.js
file and write down below code, In the below code we have connected MySQL with Nodejs using Pool connection.
=>Also, we have created a promise based method to execute the Mysql queries.
db.js:
/** * Real Time chatting app * @author Shashank Tiwari */const mysql = require('mysql'); class Db { constructor(config) { this.connection = mysql.createPool({ connectionLimit: 100, host: '127.0.0.1', user: 'root', password: 'root', database: 'chat', debug: false }); } query(sql, args) { return new Promise((resolve, reject) => { this.connection.query(sql, args, (err, rows) => { if (err) return reject(err); resolve(rows); }); }); } close() { return new Promise((resolve, reject) => { this.connection.end(err => { if (err) return reject(err); resolve(); }); }); } } module.exports = new Db();
6. Setting up the AngularJs
This topic involves how to set up the Angularjs, which means how to organize Angularjs files such as modules, services, and controllers. If you see we have created javascript files inside /js
directory, which are listed below with the usage of them.
- app.js: Initialize the AngularJs application.
- app.services.js: Contains the code for AngularJs service.
- auth.controller.js: This is controller file, used for login and registration part of the application.
- home.controller.js: Again a controller file, used in the home page of the application.
=> Now open the index.html file and write down the below markup, In the below markup we have imported all the CSS and JS files. including angular router and angular itself.
index.html:
<!-- Real Time chatting app @author Shashank Tiwari --> <!-- Defining angular app --> <html ng-app="app"> <head> <title>Realtime Private Chat using Angular, Nodejs and Mysql</title> <meta charset="utf-8"> <base href="/"> <!-- Adding CSS files--> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" > <link rel="stylesheet" href="css/style.css"> </head> <!-- Defining angular controller --> <body> <div id="main"> <!-- Angular router will inject the content here --> <div ng-view></div> </div> </body> <!-- Adding JS files --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script> <script src="https://code.angularjs.org/1.6.5/angular-route.min.js"></script> <script src="js/ui-bootstrap-2.5.0.min.js"></script> <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script> <script src="/socket.io/socket.io.js"></script> <script src="js/app.service.js"></script> <script src="js/app.js"></script> <script src="js/auth.controller.js"></script> <script src="js/home.controller.js"></script> </html>
In the above markup, we imported all the JS and CSS files, now let’s initialize the AngularJs application. In order to do this, we will use app.js
file.
=> Here will create AngularJs app and configure the application routes.
=> Also, we will import the application service class, wich we will see down the road.
app.js:
/** * Real Time chatting app * @author Shashank Tiwari */ 'use strict'; const app = angular.module('app', ['ngRoute', 'ui.bootstrap']); /* * configuring our routes for the app */app.config(function ($routeProvider, $locationProvider) { $routeProvider // route for the home page .when('/', { templateUrl: '/views/pages/auth.html', controller: 'authController' }) .when('/home/:userId', { templateUrl: '/views/pages/home.html', controller: 'homeController' }); // use the HTML5 History API $locationProvider.html5Mode(true); }); app.factory('appService', ($http) => { return new AppService($http) });
7. Writing AngularJs service
Here we will create an AngularJs service to Make HTTP call and to emit and receive socket event along with few more operation, which it will perform. Open app.service.js
and write down the below code.
=> Here we have created a common method to make HTTP call.
=> we will connect a user to a socket server, also we have written a method to emit and receive socket event from the socket server.
app.service.js:
/** * Real Time chatting app * @author Shashank Tiwari */ 'use strict'; class AppService{ constructor($http){ this.$http = $http; this.socket = null; } httpCall(httpData){ if (httpData.url === undefined || httpData.url === null || httpData.url === ''){ alert(`Invalid HTTP call`); } const HTTP = this.$http; const params = httpData.params; return new Promise( (resolve, reject) => { HTTP.post(httpData.url, params).then( (response) => { resolve(response.data); }).catch( (response, status, header, config) => { reject(response.data); }); }); } connectSocketServer(userId){ const socket = io.connect( { query: `userId=${userId}` }); this.socket = socket; } socketEmit(eventName, params){ this.socket.emit(eventName, params); } socketOn(eventName, callback) { this.socket.on(eventName, (response) => { if (callback) { callback(response); } }); } getMessages(userId, friendId) { return new Promise((resolve, reject) => { this.httpCall({ url: '/getMessages', params: { 'userId': userId, 'toUserId': friendId } }).then((response) => { resolve(response); }).catch((error) => { reject(error); }); }); } scrollToBottom(){ const messageThread = document.querySelector('.message-thread'); setTimeout(() => { messageThread.scrollTop = messageThread.scrollHeight + 500; }, 10); } }
Code explanation:
httpCall()
: In this Method, we will make HTTP call by using $http service. This method expects one parameter as an object having two properties listed below.url
: This parameter is URL, to make HTTP call.params
: Data which send over HTTP call.
connectSocketServer()
: Connects the user with Socket server.socketEmit()
: This method emits the socket event to the Socket server.socketOn()
: This method receives the socket event from the Socket server.getMessages()
: A promises based method which resolves the messages between two users.scrollToBottom()
: Used to scroll the scroll bar to the bottom of the message container.
8. Implementing Login and Registration
1. Writing markup
Till now we have completed all the setup required to run the application and connected our database to nodejs server. Now, all we have to do is write code for the application.
So let’s start with the Login and Registration operation, open the auth.html file and write down below markup.
auth.html:
<!-- Real Time chatting app @author Shashank Tiwari --> <div class="auth-page"> <div class="container auth-container"> <div class="auth"> <!-- Auth Page Header Tabs start --> <div class="auth-header"> <button type="button" class="btn btn-primary auth-header-btn" ng-click="active = 0">Login</button> <button type="button" class="btn btn-primary auth-header-btn" ng-click="active = 1">Register</button> </div> <!-- Auth Page Header Tabs ends --> <div class="auth-content"> <uib-tabset active="active"> <!-- Login Tab starts --> <uib-tab index="0"> <div class="login"> <div class="form-group"> <label for="username">Username</label> <input type="username" class="form-control" id="username" placeholder="Enter username" ng-model="data.loginUsername"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="login-password" placeholder="Enter password" ng-model="data.loginPassword"> </div> <button class="btn btn-primary" ng-click="loginUser()">Login</button> </div> </uib-tab> <!-- Login Tab ends --> <!-- Register Tab starts --> <uib-tab index="1"> <div class="register"> <div class="form-group"> <label for="username">Username</label> <input type="username" class="form-control" id="username" placeholder="Enter username" autocomplete="off" ng-model="data.regUsername" ng-keyup="initiateCheckUserName()" ng-keydown="clearCheckUserName()" /> <div ng-show='data.usernameAvailable'> <br> <div class="alert alert-danger" role="alert"> <strong>{{ data.regUsername }}</strong> Username is already taken. </div> </div> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="reg-password" placeholder="Enter password" ng-model="data.regPassword"> </div> <button class="btn btn-primary" ng-click="registerUser()">Register</button> </div> </uib-tab> <!-- Register Tab ends --> </uib-tabset> </div> </div> </div> </div>
2. Writing controller and consuming service
=> We have our markup ready, let’s create a controller for the same. Open the auth.controller.js and write down below code.
=> The below code is very easy to understand and I assume there is not much to explain. If you will read creaefully you will understand it very easily.
auth.controller.js:
/** * Real Time chatting app * @author Shashank Tiwari */ 'user strict'; app.controller('authController', function ($scope, $location, $timeout, appService) { $scope.data = { regUsername : '', regPassword : '', usernameAvailable : false, loginUsername : '', loginPassword : '' }; /* usernamme check variables starts*/ let TypeTimer; const TypingInterval = 800; /* usernamme check variables ends*/ $scope.initiateCheckUserName = () => { $scope.data.usernameAvailable = false; $timeout.cancel(TypeTimer); TypeTimer = $timeout( () => { appService.httpCall({ url: '/usernameCheck', params: { 'username': $scope.data.regUsername } }) .then((response) => { $scope.$apply( () =>{ $scope.data.usernameAvailable = response.error ? true : false; }); }) .catch((error) => { $scope.$apply(() => { $scope.data.usernameAvailable = true; }); }); }, TypingInterval); } $scope.clearCheckUserName = () => { $timeout.cancel(TypeTimer); } $scope.registerUser = () => { appService.httpCall({ url: '/registerUser', params: { 'username': $scope.data.regUsername, 'password': $scope.data.regPassword } }) .then((response) => { $location.path(`/home/${response.userId}`); $scope.$apply(); }) .catch((error) => { alert(error.message); }); } $scope.loginUser = () => { appService.httpCall({ url: '/login', params: { 'username': $scope.data.loginUsername, 'password': $scope.data.loginPassword } }) .then((response) => { $location.path(`/home/${response.userId}`); $scope.$apply(); }) .catch((error) => { alert(error.message); }); } });
3. Writing routes
Till now, we have completed the client side code for login and registration, Now let’s start writing the Nodejs routes in order to make run the application. Also, we will Mysql Queries to perform login and registration operation.
=> Open the routes.js and write down the below code. In the below I have used async/await, just to make our code synchronous and rest of the code self-explanatory.
routes.js:
/** * Real Time chatting app * @author Shashank Tiwari */ 'use strict'; const helper = require('./helper'); const path = require('path'); class Routes{ constructor(app){ this.app = app; } appRoutes(){ this.app.post('/usernameCheck',async (request,response) =>{ const username = request.body.username; if (username === "" || username === undefined || username === null) { response.status(412).json({ error : true, message : `username cant be empty.` }); } else { const data = await helper.userNameCheck(username.toLowerCase()); if (data[0]['count'] > 0) { response.status(401).json({ error:true, message: 'This username is alreday taken.' }); } else { response.status(200).json({ error:false, message: 'This username is available.' }); } } }); this.app.post('/registerUser', async (request,response) => { const registrationResponse = {} const data = { username : (request.body.username).toLowerCase(), password : request.body.password }; if(data.username === '') { registrationResponse.error = true; registrationResponse.message = `username cant be empty.`; response.status(412).json(registrationResponse); }else if(data.password === ''){ registrationResponse.error = true; registrationResponse.message = `password cant be empty.`; response.status(412).json(registrationResponse); }else{ const result = await helper.registerUser( data ); if (result === null) { registrationResponse.error = true; registrationResponse.message = `User registration unsuccessful,try after some time.`; response.status(417).json(registrationResponse); } else { registrationResponse.error = false; registrationResponse.userId = result.insertId; registrationResponse.message = `User registration successful.`; response.status(200).json(registrationResponse); } } }); this.app.post('/login',async (request,response) =>{ const loginResponse = {} const data = { username : (request.body.username).toLowerCase(), password : request.body.password }; if(data.username === '' || data.username === null) { loginResponse.error = true; loginResponse.message = `username cant be empty.`; response.status(412).json(loginResponse); }else if(data.password === '' || data.password === null){ loginResponse.error = true; loginResponse.message = `password cant be empty.`; response.status(412).json(loginResponse); }else{ const result = await helper.loginUser(data); if (result === null || result.length === 0) { loginResponse.error = true; loginResponse.message = `Invalid username and password combination.`; response.status(401).json(loginResponse); } else { loginResponse.error = false; loginResponse.userId = result[0].id; loginResponse.message = `User logged in.`; response.status(200).json(loginResponse); } } }); this.app.get('*',(request,response) =>{ response.sendFile(path.join(__dirname + '../../client/views/index.html')); /* * OR one can define the template engine and use response.render(); */}); } routesConfig(){ this.appRoutes(); } } module.exports = Routes;
4. Executing MySql queries
Open the helper.js and write down the below code in this file we will write method for login, register and other important methods which will be required for the application.
=> The below we have written method for login, register and to perform username availability check. In each method, we will run MySql query and return the result to callee function.
=> The below methods are straightforwardly written using Async/await and easy to understand.
helper.js:
/** * Real Time chatting app * @author Shashank Tiwari */ 'user strict'; const DB = require('./db'); class Helper{ constructor(app){ this.db = DB; } async userNameCheck (username){ return await this.db.query(`SELECT count(username) as count FROM user WHERE LOWER(username) = ?`, `${username}`); } async registerUser(params){ try { return await this.db.query("INSERT INTO user (`username`,`password`,`online`) VALUES (?,?,?)", [params['username'],params['password'],'Y']); } catch (error) { console.error(error); return null; } } async loginUser(params){ try { return await this.db.query(`SELECT id FROM user WHERE LOWER(username) = ? AND password = ?`, [params.username,params.password]); } catch (error) { return null; } } async userSessionCheck(userId){ try { const result = await this.db.query(`SELECT online,username FROM user WHERE id = ? AND online = ?`, [userId,'Y']); if(result !== null){ return result[0]['username']; }else{ return null; } } catch (error) { return null; } } } module.exports = new Helper();
In this part, we have completed all the initial setup and wrote code for Login and Registration.Below is the listed points which we completed in this article just for a recap,
- We created Database tables.
- We created new Nodejs Project and Did the server setup.
- Did the AngularJs setup and created all the files.
- Wrote the code for Login and Registration.
In the next part we will work on a Home page of the application and as I told earlier we will implement chat list feature. See you in next article.
This chat is amazingly good. I just love it.
Thank You!
can you please check your mail. I sent you a mail via your email contact for some kind of assistance. Thanks
please check your mail.
mate, i haven’t even finished reading it and i’m loving it already…..
Thank you
Its really very helpful man. thumps up
Thank you.
hellp, how to solution ?
help
Create one more column named as ‘online’ in ‘users’ table.
Actually I forgot to give updated SQL Queries
ok, can you please give me updates the sql query
Run this query for ‘user’ table.
Sql Query :
ALTER TABLE user ADD online varchar(2)
ok, thank you very much
why the application can not run up like in the pictures in this article? ..
when exiting an application like this:
That is great app, man.
But I got a problem when try to run [+] to view START NEW CHAT.
In this pop up, there are no Users.
Please help me explain that how to view list Users in this popup ?
Actually, Query is taking too much time to fetch record from DB. Soon I will fix this issue.
Thank you, Shashank.
I try to run DEMO, it can load list of users. Did you fix this issue ?
Please share with me how to fix that ?
Sometime, when I log out, there is an error was through out like picture below.
Please show to me how to fix that error.
Thanks a lot, it just work out of the box so nicely. I am using it with vagrant and will be adding additional chat features and will share it back.
Thanks for the great work and sharing it with us.
Hi Shashank,
Thank for your chat app, It will help me, but got a Connection error at login time, help me dear
Hey Arvind,
The connection error is most probably the mysql connection string that you have to adjust on middleware/db.js
In that file you will see something like mysql.createPool and you have to add your own connection credential there and that would take care of the problem.
already tried but not susses. Can you create custom chat (text, audio, video) as per my project requirement.
Hi Shashank,
I have tried to run your demo app. but it dosem’t work by showing these below error :
file:///C:/Users/msopheak/Desktop/chat/views/js/auth-routes.js Failed to load resource: net::ERR_FILE_NOT_FOUND
and I tried to fix it by changing the path of auth-routes.js to moddleware/auth-rotues.js
but it showing one more problem like the below image
auth-routes.js:3 Uncaught ReferenceError: require is not defined
To run nodejs app, first make sure u have installed NODEJS & Mysql (Xampp)
1. open the directory where u have your nodejs application, copy the path now go to the CMD.
2.Enter into that directory by writing cd command.
3. Now write node server.js and your application should run properly.
hope this helps.
Hi Shashank, actually i want to develop a chat application where there will be a admin and multiple users can chat with admin using nodejs & socket.io with mysql, plz help me with the logic part and functionality for this.
Hi Amit ,
You can set a flag for a specific user and use that flag to identify the admin.
And just show the chat list to the admin (if this feature required).
Hi,
Cannot find module ‘./lib/_stream_readable.js’…install lib my file readable_stream..But again show the error…can’t read stream_readable.js..
Hello,When i run server.js still show this error why?can you help me please bro?
Hello,I still show this error when i want to select to use to starting chat.i don’t know why? can you help me bro?
SAME HERE!
THE ISSUE APPEARS WHEN WE CHOOSE AN OFFLINE USER HELP!
THIS IS THE ERROR THAT CONSOLE SHOWS!!!
C:UsersMauriCDownloadsbackupschanode_modulesmysqllibprotocolParser.js:
77
throw err; // Rethrow non-MySQL errors
^
TypeError: undefined is not a function
at C:UsersMauriCDownloadsbackupschamiddlewareroutes.js:97:30
at C:UsersMauriCDownloadsbackupschamiddlewarehelper.js:202:8
at C:UsersMauriCDownloadsbackupschamiddlewarehelper.js:254:7
at Query._callback (C:UsersMauriCDownloadsbackupschamiddlewarehelper.
js:16:9)
at Query.Sequence.end (C:UsersMauriCDownloadsbackupschanode_modulesmy
sqllibprotocolsequencesSequence.js:96:24)
at Query._handleFinalResultPacket (C:UsersMauriCDownloadsbackupschanod
e_modulesmysqllibprotocolsequencesQuery.js:144:8)
at Query.EofPacket (C:UsersMauriCDownloadsbackupschanode_modulesmysql
libprotocolsequencesQuery.js:128:8)
at Protocol._parsePacket (C:UsersMauriCDownloadsbackupschanode_modules
mysqllibprotocolProtocol.js:280:23)
at Parser.write (C:UsersMauriCDownloadsbackupschanode_modulesmysqlli
bprotocolParser.js:73:12)
at Protocol.write (C:UsersMauriCDownloadsbackupschanode_modulesmysql
libprotocolProtocol.js:39:16)
please help!!!
check database name middleware/db.js make sure database name is same
This app is amazing, very help me to create my thesis, thanks, Btw can you help me how to create a group chat?
In a group chat, You can use ‘io.emit()’ to send message to all users connected to socket instead of sending messages to specific user.
More on Broadcasting messages : http://socket.io/docs/#broadcasting-messages
i just cotomized your app shashank, but where i can live or hosting this app?
You have multiple options for ex. DigitalOcean , Heroku and RHCluoud (Openshift)
& they have good documentation.
Ok i will try, and then, why the contact isn’t appear in modal contact?
hi ,i am getting the below error. please give solution and reason for the below error
[Error: UNKNOWN_CODE_PLEASE_REPORT: Expression #1 of ORDER BY clause is not in SELECTlist, references column ‘chat.conversation.timestamp’ which is not in SELECT list; this is incompatible with DISTINCT]
code: ‘UNKNOWN_CODE_PLEASE_REPORT’,
errno: 3065,
sqlState: ‘HY000’,
index: 0 }
Query failed
{ [Error: UNKNOWN_CODE_PLEASE_REPORT: Expression #1 of ORDER BY clause is not in SELECT list, references column ‘chat.conversation.timestamp’ which is not in SELECT list; this is incompatible with DISTINCT]
code: ‘UNKNOWN_CODE_PLEASE_REPORT’,
errno: 3065,
sqlState: ‘HY000’,
index: 0 }
Query failed
Hi, Is it possible to use the socket session in other page? For example, let’s say you are in home page, an someone texted you from chat page. So is it possible to notify the person who is in home page and not in chat page??
Currently, it let notify if both the person in the same chat page,
Also, is it possible to get the sane feature without using angular and using jQuery
Sorry for late reply.
Yes, is it possible give it a shot.
and am not sure what you mean by ‘without using angular and using jQuery’ !
As long as socket is concerned to get update from server, you will require socket library.
Hi, I tried settup this app in my localhost but “_userinfo Failed to load resource: the server responded with a status of 404 (Not Found)”, all route can not access. Please help me run success this app! thanks you!
Am getting the following error $scope.msgs.push is not a function 🙁
If any one has insights it would be much appreciated.
I have a relatively basic question. I have read through the first part of this tutorial and I have been able to follow along for the most part. I have a my own project that uses similar technology, and incorporates a login page. I am having a little trouble gluing everything together. Specifically I am confused how he has integrated Angular.js with his web server. A better example of what I mean, when his login-register contrller posts a login or a register request, how does his web server know to handle it, i.e why does his autu-routes class get triggered? I do not see any code telling it what URL or host to use. Can any explain why a post request gets automatically handled by his web server?
please can anyone help me. I am stuck in registration process. when I click the register after entering the requirements I get connection error. And console shows this
https://uploads.disquscdn.com/images/de93049f597dbb8cac7eb7b1e426cb1a6272b1476baa7e67185a6af5ed480b9a.png
Did you try with admin privileges?
Hello I am getting the following error https://uploads.disquscdn.com/images/6c9257ab958b4a15190379d4fdf22cf6edd2dcd0c9e19470561d207f65733125.png can anyone help?
Hi Prabhakar ,
please make sure you are passing the app variable in a route function.
https://uploads.disquscdn.com/images/dd0aef72abd42b3bb7d2e243b0e22525190d0ce1c9dfd3a920023bd9d6987f24.png
hii shashank , i got continuasly alert of connection error please help me for further
Hi,
Can you please post the error that you are getting in your console ?
OK https://uploads.disquscdn.com/images/4f1079b08891d50319ef1f54e7cd5760f0550396101eb1b9f10447e117d805ed.png , Here is this
Sorry for late reply drashti ,
The reason for this error : con object is undefined
On line number 202 in auth-route file.
How to fix it :
Make sure you are passing connection object to auth-route file in server.js.
Then in auth-route file, you must receive that connection object as a parameter to run your mysql queries.
how to fix this?
In your auth-routes file, on line number 137.
Change -> id:”. to -> id:null,
please give me solution
hi your site doesn’t support resume for download? i can’t download it could you please solve this problem…
or send it by email…
thanks…
Conversation: This table holds the conversation Id between users.
why do we need conversation id? @ShankyTtiwari:disqus
You are a true observer.
For some reason I created that column and I think I forgot to remove that column please ignore I will update the code.
Hi i’m trying to download, but it stops at half for some reason.. any idea why?
Hi … Thank you for your application and it work 100% … i want just add firstname and lastname in register page … can you please help me
A newbie ,pls help https://uploads.disquscdn.com/images/be2f2163cf63dcf5254e2baff517ddbfeb2f3482a788263459f1550ea5fbdc0f.png
Erro 🙁
can you please try sudo.
Example,
sudo node server.js
hello shashank,m new to node n angular both.trying to make ur application work on my computer,which doesnt have internet connection…help me how can I log in or register??I have created a database with few entries using sqlYog for this purpose.as i enter credentials it throws connection error..
You don’t need a Internet connection only If you are creating this application.And I assume you are connected to your localhost DB in SQLYog. If you are creating login and Register for this app, please refer to source code of this article.
ok.i am doing exactly the u have done in ur part-1.but after that what shud i enter so that i could log in..plz help.i want to make this app work.and why it is saying connection error..and in console it is saying “cannot read property ‘ release’ of undefined”.
I assume that u have already created a login page and registration page. The
First step is you need to register a new user Then you can log in using that user’s Password and username.
This error is related to Mysql. Can you please post image of that error, that would be very helpful.
thank u very much for your prompt replies.below I m attaching the image of the error n firebug console also. https://uploads.disquscdn.com/images/5bbaa9f2b7afcba8b1997e81f14813a0af5b26b7b9ab9cb8655e276f965d7676.png
con.release();
, This line is giving error because you are gettingcon
as undefined. check your mysql server is running or not. If yes check the MySql connection with your app.Check how to connect nodejs with MYsql
Link :=> https://codershood.info/2015/12/09/connecting-nodejs-app-to-mysql/
Instead of mysql can i use postgresql? Do you have the repo for that? Thanks.
Yes You can use postgresql, and sorry as of now I don’t have any repo for that
Hi, Great app,
I am try to run login.html on my local server, but i get error as image on bottom of text. I am put correct access data in db.js
host : ‘localhost’,
user : ‘root’,
password : ”,
database : ‘chat’
, so i can not figure why can not signin. why i am get this error.
https://uploads.disquscdn.com/images/bcd12b17f5b91c3f861d5218734a17c0d60753359da094b3f39434cfb79a734d.jpg
Am getting the following error
{ [Error: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect integer value: ” for column ‘id’ at row 1]
code: ‘ER_TRUNCATED_WRONG_VALUE_FOR_FIELD’,
errno: 1366,
sqlState: ‘HY000’,
index: 0 }
Query failed
Hi vijay,
This might help you ,
Link=> https://stackoverflow.com/questions/31698871/er-truncated-wrong-value-for-field-on-saving-some-strings-to-mysql
Can we manage local storage for storing messaging for next time view ?
Is there any build in module like store chatting message for next time views then please share with me.
Since you are storing the messages in Mysql, You can actually add the functionality to view the old messages. I don’t see any need to use local storage. and as of now am not familiar with any such module.
Okay, Thanks.
Actually, I want to see my old message when i don’t have internet connection.
So, I was asking, Okay, We will manage it by using Pouch DB for full fill the requirement.
Hello Shashank,
I have some question in my mind, Please share your views on it.
Can we use this chatting module with lot’s of user?
Do you tested with any limitation of users, How many user can chat with this chat modules?
Can make call by android and iOS socket.io as we are using socket.io at angular end.?
1 . Can we use this chatting module with lot’s of user?
=> Yes You can. Provided You should implement clustering and check if you have any memory leaks.
2 . Do you tested with any limitation of users, How many user can chat with this chat modules?
=> No.
3 .Can make call by android and iOS socket.io as we are using socket.io at angular end.?
=> I don’t have much experience in Mobile app development, But still If you are creating Hybrid apps using Ionic or something, then yes you can call socket.io from there too. And if you are creating native apps then there must be socket libraries for the same.
Thanks,
hi Shashank,am getting this error.
Please help me..
error: https://uploads.disquscdn.com/images/e210ee6878bdb17b6a33c7fb7ab9a0eafc71e41788499e9e667ae8d323a80da6.png https://uploads.disquscdn.com/images/4acc0f8b06ffea6e3fad24f744b08d997a828e1d5dc2cd20c68fee1e955d0acb.png
error https://uploads.disquscdn.com/images/fd6cd1a3af3101a22a08612c9227be3c44373f7d9c9848adbbb6d3a78884ea17.png
You are getting this error bcoz your con object is undefined. Make sure your con object holds a connection.
Thank you shashank its working now…
Yоu’rе welcome
Hello Shashank,
Suppose, I am logged in with A user in separate Browser and with B user in third Browser then B user send message to A user,
First browser A user is getting messages but the second browser A user is not getting the message.
As, I have checked code we are adding socket in users array but due to already existing socket with user A id it’s not adding for second browser A user,
Can you please let me know, How we can overcome this issues ?
Two choices ,Either Store the socket id’s in an array or mare sure user can’t logic anywhere else if he/she is already logged in.
Thanks,
One more things, If multiple user are logged in a device, then socket will be available for them all the time it will create many number of socket on server that will decrease performance of chatting is there any solution for this problem.
If multiple socket are open on server then we need to increase RAM of server, Right?
Few things you can do here such as clustering,check if you have any memory leakage, Cache Static Files and Implement a Node.js Load Balancer on the server.
There are lot of things that you can do.
As far as this code is concerned, it’s little messy Soon I will update this article using Nodejs version 8.
Hello Shashank,
Need your help !!
What is process of disconnect?
I have seen code there are a socket.on(‘disconnect’ method on server end but didn’t find emit method on front end code,
Can you please elaborate disconnect and exit functionality so that I can do free socket once didn’t need and do some operation like offline user on that action.
Hey man your great! Look I made my own site and i am adding new things. By the way i am 18 and a graduating student in Computer Studies. I have the this picture as a proof. https://uploads.disquscdn.com/images/b8cba8c847e168520340de5e58d0dfec676a5ada6bf74cf851b3ade409f0e94d.png
how can i run this script on a specified url like
http://sosolutions.com.pk/projects/chat3/
Sorry for the delay, I assume you are asking to me, How to host a Nodejs app in production.
Please follow this URL : https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04
Hope this helps.
HI Shashank,
I got this error, i didn’t get the how to solve error
****************************************************
{ [Error: UNKNOWN_CODE_PLEASE_REPORT: Expression #1 of ORDER BY clause is not in SELECT list, references column ‘chat.conversation.timestamp’ which is not in SELECT list; this is incompatible with DISTINCT]
code: ‘UNKNOWN_CODE_PLEASE_REPORT’,
errno: 3065,
sqlState: ‘HY000’,
index: 0 }
****************************************************************************
{ [Error: ER_WRONG_FIELD_WITH_GROUP: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘chat.conversation.to_id’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by]
code: ‘ER_WRONG_FIELD_WITH_GROUP’,
errno: 1055,
sqlState: ‘42000’,
index: 0 }
Query failed
Can you print the query and try to run in the MySql CMD or in Interface ?
Did you solved this issue?
in this project you are storing the user data or msges in local database..?
or it can be run from anywhere?
I didn’t get you here can you please elaborate more ?
i wanted to implement it as a part of my application so for storing the data of multiple user on different 2 device …do i need to implement service to store the data into the database??.
Okay , So from your question I assume you have application and you wanna integrate this app into it.
Yes you will require a database to store messages between users. You are free to use any database as long as you are comfortable with it.
For example this post will you give idea how I used MongoDB to store messages chatlist and user’s information.
I am storing messages in MySql DB.
Hi, chat application now i am running in http://127.0.0.1:81/home#?id=2 link, how to intergrate into our project, and how to run our my local folder
Sorry for late reply.
First point => That depends on your project/Application in which you want to integrate this app. If it’s a website then than it should be easy to do that.You can remove the logIn and logout screen from this app and directly show the chat page. Remember login should be handled behind the screen or you can simply remove the login and logout feature from this app if your current application already filled with it.
Second Point (Running on ur local folder) => You can always map any url to http://127.0.0.1:81, on your local environment my using the Host file.
I hope this helps.
Yeah ok thank you,but i have more doubt I don’t know node js, in this chat application running on using cmd prompt, I don’t want like that.i am going to integrate my project that is middle level project.i have lot of modules.now I running on my own domain for example http://www.example.com that is using angularjs,php and MySQL. what I need in this chat application will integrate into my project (using above mentioned language). anyone please help me this is very important for me
i having this problem please help me out i want this chat system to embed in my website https://uploads.disquscdn.com/images/ca5b11770dac6cf6232552894ce05e99bfa0d613519caeef4be443e828efb25a.png
https://uploads.disquscdn.com/images/830571b93578e1fd3a2a7fc456db9899dba8441d99d2db50d3106ab58532623c.png
error
Yes, this is Unhandled promise Rejection. You can use
or
I will update the code soon.
I have tested this application and find it to be very good. There are two points which i would like to clarify / seek help on.
1) Is there a way to show an alert when a new message is received? If there are many users, how does one know if they have received a new message?
2) If you type the complete logged in address on the address bar e.g. [domain]/home/1 it automatically logs you in. You can log in as other users by changing the last digit, bypassing the login page. Is there any way to avoid this?
Thanks.
Thank you!
Absolutly both the points can be easily added,
1. Notification whenever you receive new message:
To show notifications, you can use any library for example Angularjs toaster .
home.controller.js:
2. Bypassing the login page
I think I forgot to check this, I will update the code. In the mean time you can use
resolve for AngularJs route
.Just a note,
In case if you code in Angular,
1. Notification.
I have implemented it in angular 2, you can download the above mentioned Ebook.
1.Bypassing Login.
You can check this github repo, I have used Angular gaurds.
I hope this helps.
Hi Shashank,
Thank you for your prompt reply. I will try these.
Cool.
Hi I was in the middle of making my own offline social media. I am using php for admin and saving the database then I am using node js to run the program for users chat , posing some images. The thing is I wanted to know if you can help me learn more about node js. I am new to node js but I can handle simple logical about this program. I am happy to learn more about this thing, it makes me want to acquire this to grow node js as base programming of mine.
PS. I used .bat file to run the server. I t helps me a lot, what do you think of this
Hi there,
Sorry for replying late. I assume you have good knowledge of Javascript. First I would suggest you to learn ExpressJs(a Nodejs Web framework), though there are many other frameworks as well such as hapi.js and many more.
ExpressJs is widely used and has a great community behind it. Also, you can give try to Hapi.js as well. Use whatever you like.
After that learn by building stuff and then step by step increase difficulty level of projects. You can start with,
1. CRUD app (You will get knowledge of express router n all)
2. Real-time message notification ( you will understand real-time goodness)
3. Create a real-time chat (Combine above two)
4. Create Image gallery app (Use external modules such as OpenCV and sharp to crop images and save them into folder.)
Hope this helps.
Hi, I used this chat app its very helpful for me but I want to implement rest api for this type of chat for android application. can you help me?
Hi @bhoomi_solanki:disqus Sorry for replying late.
In this application HTTP server and Socket server both run on the same port, so here you don’t need to change anything at least in the nodejs server. It can be consumed as REST API as it is.
The challenge would be listing the Socket event from the server, So for that, you need to use some Socket client for Android (Am sure you know this 🙂 ).
You may use Socket.io’s Andoid client.
Hi, I really like this chat app and was wondering if you know how to make it connected to Microsoft SQL Server Management Studio instead of MySQL? Thank you.
hello shashank
this chat module working good but can you suggest me how can i share image and docs in this chat
Hi Pramod,
1. First, you would upload the images/doc to the Nodejs server from AngularJs.
2. Add one more column in message table, say
doc
.2. While uploading on the server side, insert the path of that doc/image.
3. When you fetch messages from the message table, extract the extension using path that you just saved.
4. And based on that extension render your doc, say if that doc is image than you can render it easily and if that doc is PDF then you can display some PDF indicating image followed by a link to that PDF and Some title to it(you can use it message column for this).
5. Or instead of extracting the extension type of doc, just add one more column in the message table, say
type
. In this column, you can store the type of DOC.6. While fetching data from message table you don’t have to extract the extension type. Just make sure you are inserting the type while uploading the DOC.
Hope this helps.
hi shashank thank for your replay I tried as you said but I am not able to properly upload image and show in chat . can you share code and blogs those are help in file shareing . thanx in advance.
Hi Pramod,
I have already divided this article into three parts, adding this feature will make the articles way too lengthy. So, I won’t add this feature at least, not in these articles.
Yes, writing a new parts of this series is possible. But due to my day job, I am on a very tight schedule. A lot of tasks and articles are pending.
But in near future, I will definitely add this feature, so please I request you to bear with me.
But for the time being, You can email (shashank[at]codershood.info) your code to me or create GitHub repo. I will add the pseudo code in your project.
By the way what problems you are facing. There two steps first uploading the image and the second is displaying the image. At which part you are stuck?
hello shashank hope you doing well ,I’ve added the image share
function according to your suggestion and work fine thnx for this. Can
you help me another i want to add this in my codeigniter project so how
can i do this
Oh man, am really very sorry, I opened your email that day and then got into something else and forgot to check. I apologize, but it’s great you did it by your self, wonderful.
For CodeIgniter, you can write all the functionalities except real-time message transferring part. I hope you understand the difference between TCP and HTTP. So you need a TCP server in order to have real-time communication.
Now if you can’t have that for some reason, you can use an external source such as a pusher.
But I would suggest you to have Nodejs server and combine with the existing PHP app.
Hope this helps.
first of all ur creation is awesome and i got the output.now i wanted provide the typing status in this creation itself..so please send the code inorder to create the typing status in this chatroom itself.
Hey you can do something like that by referring this post, let me know if you get stuck somewhere.
hello im trying to run the app but i get an error how can i fix this
error:
internal/modules/cjs/loader.js:800
throw err;
^
Error: Cannot find module ‘express’
Require stack:
– C:\Users\melis\ChatApp\server.js
[90m at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797:15)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:690:27)[39m
[90m at Module.require (internal/modules/cjs/loader.js:852:19)[39m
[90m at require (internal/modules/cjs/helpers.js:74:18)[39m
at Object. (C:\Users\melis\ChatApp\server.js:7:18)
[90m at Module._compile (internal/modules/cjs/loader.js:959:30)[39m
[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)[39m
[90m at Module.load (internal/modules/cjs/loader.js:815:32)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:727:14)[39m
[90m at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)[39m {
code: [32m’MODULE_NOT_FOUND'[39m,
requireStack: [ [32m’C:\\Users\\melis\\ChatApp\\server.js'[39m ]
}
Hey Lissa, Sorry for replying late.
Can you run
npm i
in root of the project directory. The command will install all the Nodejs dependencies and you will no longer get this error. If you do let me know.Thanks,
hey i want to add delivered and read status of message could you explain me.
how should i add these response of read and delivered.. btw thank you for this amazing post
hey the session is not working in this code and also the error message now showing and the blank message are also inserting in database
session is not working