<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Chat Application in Node JS &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/chat-application-in-node-js/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Mon, 04 Dec 2017 12:27:03 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Chat Application in Node JS &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io</title>
		<link>https://sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/</link>
					<comments>https://sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 04 Dec 2017 12:09:50 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node JS]]></category>
		<category><![CDATA[Chat Application in Node JS]]></category>
		<category><![CDATA[Chat Application using Socket.io]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Simple client side chat application]]></category>
		<category><![CDATA[Socket.io]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12595</guid>

					<description><![CDATA[[toc] Introduction In this article, we are going to a chat application in Node JS  with the back end MongoDB.  We will also be using Mongoose for creating the MongoDB models and Socket.io for making multi directional chats on multiple client window. If you are really new to the Node JS, I strongly recommend you to read some articles on the same here. You can also see how you can create a sample Node application with MongoDB and Mongoose here. At the end of this article, I guarantee that you will be having some basic knowledge on the mentioned technologies. I hope you will [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this article, we are going to a chat application in <a href="http://sibeeshpassion.com/category/Node-JS/">Node JS</a>  with the back end <a href="http://sibeeshpassion.com/category/MongoDB">MongoDB.</a>  We will also be using <a href="http://sibeeshpassion.com/tag/Mongoose/">Mongoose</a> for creating the MongoDB models and <a href="http://sibeeshpassion.com/tag/Socket.io/">Socket.io</a> for making multi directional chats on multiple client window. If you are really new to the Node JS, I strongly recommend you to read some articles on the same <a href="http://sibeeshpassion.com/category/Node-JS/">here</a>. You can also see how you can create a sample Node application with MongoDB and Mongoose <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">here</a>. At the end of this article, I guarantee that you will be having some basic knowledge on the mentioned technologies. I hope you will like this article.</p>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://code.msdn.microsoft.com/ChatApp-NodeJS-Socketio-22325371">here</a></p>
<h3>Background</h3>
<p>Creating a chat application is always an interesting this to do. And it is a good way to learn a lot, because you are creating some interactions on your application. And with the release of few technologies we can create such application without any hassle. It is much more easier than ever. Here we are also going to create a chat application. A basic knowledge of Node JS, MongoDB, JavaScript, JQuery is more than enough to create this project. So, please be with me. Let&#8217;s just skip the talking and start developing.</p>
<h3>Setting up Node application</h3>
<p>This step requires some basic knowledge, please see some of that <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">here</a>.  So as mentioned in that article, we have successfully created our Package.json file and installed the required packages. Let&#8217;s review our package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
 "name": "chatapp",
 "version": "1.0.0",
 "description": "A chat application in Node JS, which uses MongoDB, Mongoose and Socket.io",
 "main": "index.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
 },
 "keywords": [
 "Node",
 "JS",
 "MongoDB",
 "Mongoose",
 "Socket.io"
 ],
 "author": "Sibeesh Venu",
 "license": "ISC",
 "dependencies": {
 }
}
</pre>
<p>Let&#8217;s install the packages now by running the below commands.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save express
npm install --save mongoose
npm install --save body-parser
npm install --save socket.io</pre>
<p>Now that we have all the dependencies added to the package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mongoose": "^4.13.6",
    "socket.io": "^2.0.4"
  }</pre>
<h4>Creating an App using Express</h4>
<p>Let&#8217;s create a file server.js and build an app using Express.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var app = express()
app.listen(3020,()=&gt;{
 console.log("Well done, now I am listening...")
})</pre>
<p>I hope you are getting  the desired output, if not, please don&#8217;t worry, just double check the codes you had written.</p>
<h4>Running our application on browser</h4>
<p>Let&#8217;s run our application on port 3020 and see what we are getting <a href="http://localhost:3020/">http://localhost:3020/</a>..</p>
<p>Yes you will get an error as <code class="EnlighterJSRAW" data-enlighter-language="js">Cannot GET /</code>  , no worries. To fix that you need to add the following code block to your server.js file</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.use(express.static(__dirname))</pre>
<h4>Creating Index page</h4>
<p>Here I am going to create a <a href="http://sibeeshpassion.com/category/HTML5/">HTML 5</a> page with <a href="http://sibeeshpassion.com/category/JQuery/">JQuery</a> and Bootstrap referenced in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;!DOCTYPE html&gt;
&lt;title&gt;Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io&lt;/title&gt;
&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" crossorigin="anonymous"&gt;
&lt;script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;
&lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;

&lt;div class="container"&gt;
    &lt;br&gt;
    &lt;div class="jumbotron"&gt;
        &lt;h1 class="dispaly-4"&gt;Start Chatting&lt;/h1&gt;
        &lt;br&gt;
        &lt;input id="txtName" class="form-control" placeholder="Name" type="text"&gt;
        &lt;br&gt;
        &lt;textarea id="txtMessage" class="form-control" placeholder="Message"&gt;&lt;/textarea&gt;
        &lt;br&gt;
        &lt;button id="send" class="btn btn-success"&gt;Send&lt;/button&gt;
    &lt;/div&gt;
    &lt;div id="messages"&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>As you can see, the page has two text boxes and one button. We will be creating some scripts very soon which uses these controls.</p>
<h3>Start developing the chat app</h3>
<p>Till now, it was all basic, and we have done it well. Now it is time to go and write some advanced codes. So, are you ready?</p>
<h4>Create model from page data</h4>
<p>Here we are going to create the model from the page data, that is, from the controls we have in our page. We will be using JQuery to do so.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">&lt;script&gt;
    $(() =&gt; {
        $("send").click(() =&gt; {
            var chatMessage = {
                name: $("#txtName").val(), chat: $("#txtMessage").val()
            }
            postChat(chat)
        })
    })

    function postChat(chat){
        console.log(chat)
    }

&lt;/script&gt;</pre>
<p>Now that we have got the model from the user, let&#8217;s save it to the DB.</p>
<div id="attachment_12596" style="width: 428px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Model-values-on-browser-console.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-12596" class="size-full wp-image-12596" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Model-values-on-browser-console.png" alt="Model values on browser console" width="418" height="446" srcset="/wp-content/uploads/2017/12/Model-values-on-browser-console.png 418w, /wp-content/uploads/2017/12/Model-values-on-browser-console-281x300.png 281w, /wp-content/uploads/2017/12/Model-values-on-browser-console-400x427.png 400w" sizes="(max-width: 418px) 100vw, 418px" /></a><p id="caption-attachment-12596" class="wp-caption-text">Model values on browser console</p></div>
<h4>Setting up database</h4>
<p>We are going to set up our database in mLab as mentioned in this article <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">Using MongoDB on Node JS Application Using Mongoose.</a> So let&#8217;s just require Mongoose and do the needed changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var mongoose = require("mongoose")

var app = express()

var conString = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"
app.use(express.static(__dirname))

var Chats = mongoose.model("Chats", {
    name: String,
    chat: String
})

mongoose.connect(conString, { useMongoClient: true }, (err) =&gt; {
    console.log("Database connection", err)
})

app.listen(3020, () =&gt; {
    console.log("Well done, now I am listening...")
})</pre>
<h4>Creating a Post request</h4>
<p>Now let&#8217;s create a post requests in our index.html file which will the post API in our server.js file.</p>
<p><em><span style="text-decoration: underline;">index.html</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">function postChat(chat) {
        $.post("http://localhost:3020/chats", chat)
}</pre>
<p><span style="text-decoration: underline;"><em>server.js</em></span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.post("/chats", async (req, res) =&gt; {
    try {
        var chat = new Chats(req.body)
        await chat.save()
        res.sendStatus(200)
    } catch (error) {
        res.sendStatus(500)
        console.error(error)
    }
})
</pre>
<p>Let&#8217;s just run our application and test it out.</p>
<p>You may be getting an error as &#8220;(node:10824) DeprecationWarning: Mongoose: mpromise (mongoose&#8217;s default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html&#8221;&#8221;, here to fix this, we need to use the default promise instead of the Mongoose promise. Let&#8217;s change that. Add this code <code class="EnlighterJSRAW" data-enlighter-language="js">mongoose.Promise = Promise</code> to our server.js file. Give it a try after setting it.</p>
<p>Still it is not working right, you are getting <em>undefined </em>at the place, <code class="EnlighterJSRAW" data-enlighter-language="js">var chat = new Chats(req.body)</code> in our Post API . At this stage, we will have to use our body-parser packages, do you remember the package we have installed? Let&#8217;s just require that package <code class="EnlighterJSRAW" data-enlighter-language="js">var bodyParser = require("body-parser")</code> add the preceding codes to our server.js file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))</pre>
<p>Now this will convert the request to a JSON object by default. Give it a try again, I am sure you will get the actual value instead of undefined.</p>
<h4>Creating a Get request for all the chat data</h4>
<p>We have written codes to write our data into our database, we will have to show this data on our page right? Here we are going to write the get requests in out index.html page which will call the get API.</p>
<p><em><span style="text-decoration: underline;">index.html</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">function getChats() {
     $.get("/chats", (chats) =&gt; {
         chats.forEach(addChat)
     })
}

function addChat(chatObj){
    $("#messages").append(`&lt;h5&gt;${chatObj.name} &lt;/h5&gt;&lt;p&gt;${chatObj.chat}&lt;/p&gt;`);
}</pre>
<p>And call the function getChats() in document ready event.</p>
<p><em><span style="text-decoration: underline;">server.js</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.get("/chats", (req, res) =&gt; {
    Chats.find({}, (error, chats) =&gt; {
        res.send(chats)
    })
})</pre>
<p>Here we are passing {} to our find function, this means, we are going to get all the chats without any filter. Just run your application now, and check whether you are getting the chat messages you had sent.</p>
<div id="attachment_12597" style="width: 369px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png"><img decoding="async" aria-describedby="caption-attachment-12597" class="size-full wp-image-12597" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png" alt="Retrieving data from a MongoDB" width="359" height="514" srcset="/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png 359w, /wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB-210x300.png 210w" sizes="(max-width: 359px) 100vw, 359px" /></a><p id="caption-attachment-12597" class="wp-caption-text">Retrieving data from a MongoDB</p></div>
<h3>Implementing Socket.io</h3>
<p>Now the chat we are sending is getting saved to our database and we are able to load the same on page load. Is it the behavior of a perfect chat application? Absolutely no, a perfect chat application will be able to,</p>
<ol>
<li>Show the chat message to the UI right after the data gets inserted to database</li>
<li>Show the chats in multiple clients, here in our application, if you are opening the URL in multiple browser instance, and if you need to show the chats to both instances, you will have to refresh the pages right? This is not a recommended way</li>
</ol>
<p>That&#8217;s why we are going to implement Socket.io in our application.</p>
<h4>Require the package</h4>
<p>Unlike the other packages, adding socket.io to the application is a different process, we will have to require the http server first, then, set our app. You can see more information on socket.io <a href="https://socket.io/">here</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var http = require("http").Server(app)
var io= require("socket.io")(http)</pre>
<h4>Enabling the connection</h4>
<p>To enable the connection, we need to use the function io.on.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">io.on("connection", (socket) =&gt; {
    console.log("Socket is connected...")
})</pre>
<h4>Listen using new http server</h4>
<p>Now that we have a new http server, and we should change our listen code to our new http.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var server = http.listen(3020, () =&gt; {
    console.log("Well done, now I am listening on ", server.address().port)
})</pre>
<h4>Changes in script</h4>
<p>Let&#8217;s do listen for the event &#8220;chat&#8221; now in our html page.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var socket = io()
socket.on("chat", addChat)</pre>
<p>Please do not forget to include the socket.io.js reference in our index page, other wise you may get an error as &#8220;Uncaught ReferenceError: io is not defined&#8221;</p>
<h4>Emits the event</h4>
<p>Once the above step is completed we need to make sure we are emitting the new event on our Post API.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.post("/chats", async (req, res) =&gt; {
 try {
 var chat = new Chats(req.body)
 await chat.save()
 res.sendStatus(200)

 //Emit the event
 io.emit("chat", req.body)

 } catch (error) {
 res.sendStatus(500)
 console.error(error)
 }
})</pre>
<p>&nbsp;</p>
<p>Let&#8217;s just run our application in two browser instances and check for the output.</p>
<div id="attachment_12598" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Socket.io-Output-e1512388473997.png"><img decoding="async" aria-describedby="caption-attachment-12598" class="size-full wp-image-12598" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Socket.io-Output-e1512388473997.png" alt="Socket.io Output" width="634" height="596" /></a><p id="caption-attachment-12598" class="wp-caption-text">Socket.io Output</p></div>
<p>Please make sure that you are getting the chats in the second instance when you send it from the first instance of the browser and vice versa.</p>
<p>&nbsp;</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
