<?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>Christophe Coenraets &#187; Node.js</title>
	<atom:link href="http://coenraets.org/blog/category/node-js/feed/" rel="self" type="application/rss+xml" />
	<link>http://coenraets.org/blog</link>
	<description>Web Platform, Cloud and Mobile Application Development</description>
	<lastBuildDate>Mon, 13 May 2013 16:05:20 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Implementing RESTFul Services with Node.js and MongoDB</title>
		<link>http://coenraets.org/blog/2013/04/implementing-restful-services-with-node-js-and-mongodb/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=implementing-restful-services-with-node-js-and-mongodb</link>
		<comments>http://coenraets.org/blog/2013/04/implementing-restful-services-with-node-js-and-mongodb/#comments</comments>
		<pubDate>Thu, 18 Apr 2013 17:04:19 +0000</pubDate>
		<dc:creator>Christophe Coenraets</dc:creator>
				<category><![CDATA[Backbone.js]]></category>
		<category><![CDATA[Express]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node.js]]></category>

		<guid isPermaLink="false">http://coenraets.org/blog/?p=5516</guid>
		<description><![CDATA[In my previous post, I shared a new version of the Employee Directory sample application. By default, the application uses an in-memory data store to provide a &#8220;download and run&#8221; experience (no need to set up a server or a database). In this post, I&#8217;ll show how to replace the in-memory data store with RESTful [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://coenraets.org/blog/wp-content/uploads/2013/04/nodejs-mongodb.png"><img src="http://coenraets.org/blog/wp-content/uploads/2013/04/nodejs-mongodb.png" alt="" title="nodejs-mongodb" width="640" height="120" class="alignleft size-full wp-image-5614" /></a><br />
In my <a href="http://coenraets.org/blog/2013/04/sample-application-with-backbone-js-and-twitter-bootstrap-updated-and-improved/">previous post</a>, I shared a new version of the Employee Directory sample application. By default, the application uses an in-memory data store to provide a &#8220;download and run&#8221; experience (no need to set up a server or a database). In this post, I&#8217;ll show how to replace the in-memory data store with RESTful services powered by Node.js, MongoDB and the Express framework. </p>
<div class="woo-sc-box info   ">
If you are not using the Employee Directory sample application, you can still use this post on its own to learn how to implement RESTful services with Node.js, MongoDB and the Express framework.<br />
</div>
<h4>Step 1: Install Node.js</h4>
<p>If it&#8217;s not already installed on your system, follow the steps below to install Node.js:</p>
<ol>
<li>Go to <a href="http://nodejs.org">http://nodejs.org</a>, and click the <em>Install</em> button.</li>
<li>Run the installer that you just downloaded. When the installer completes, a message indicates that <em>Node was installed at /usr/local/bin/node</em> and <em>npm was installed at /usr/local/bin/npm</em>. At this point node.js is ready to use.</li>
</ol>
<h4>Step 2: Install MongoDB</h4>
<p>If MongoDB is not already installed on your system, refer to the <a href="http://www.mongodb.org/display/DOCS/Quickstart">MongoDB QuickStart</a> for platform-specific installation instructions. Here are some quick steps to install MongoDB on a Mac:</p>
<ol>
<li>Go to <a href="http://www.mongodb.org/downloads">http://www.mongodb.org/downloads</a> and download the latest OS X 64-bit production release (2.4.2 at the time of this writing).</li>
<li>In Finder, double-click mongodb-osx-x86_64-2.4.2.tgz to extract its contents. (Alternatively you can use: tar -zxvf mongodb-osx-x86_64-2.4.2.tgz)</li>
<li>Move the mongodb-osx-x86_64-2.4.2 folder to /usr/local (or another folder according to your personal preferences):
<pre class="brush: bash; light: true; title: ; notranslate">
sudo mv -n mongodb-osx-x86_64-2.4.2/ /usr/local/
</pre>
</li>
<li>(Optional) Create a symbolic link to make it easier to access:
<pre class="brush: bash; light: true; title: ; notranslate">
sudo ln -s /usr/local/mongodb-osx-x86_64-2.4.2 /usr/local/mongodb
</pre>
</li>
<li>Create a folder for MongoDB&#8217;s data and set the appropriate permissions:
<pre class="brush: bash; light: true; title: ; notranslate">
sudo mkdir -p /data/db
sudo chown `id -u` /data/db
</pre>
</li>
<li>Start mongodb
<pre class="brush: bash; light: true; title: ; notranslate">
cd /usr/local/mongodb
./bin/mongod
</pre>
</li>
</ol>
<h4>Step 3: Download the Code</h4>
<p>The Node.js code for the Employee Directory RESTful services is available in <a href="https://github.com/ccoenraets/directory-rest-nodejs">this<a/> GitHub repository. Download it <a href="https://github.com/ccoenraets/directory-rest-nodejs/archive/master.zip">here</a> and unzip the file anywhere on your file system.</p>
<p>Open server.js and routes/employee.js in a code editor. The RESTFul API is defined as follows:</p>
<table style="margin-bottom:24px;">
<tr>
<th>Method</th>
<th>URL</th>
<th>Action</th>
</tr>
<tr>
<td>GET</td>
<td>/employees</td>
<td>Retrieve all employees</td>
</tr>
<tr>
<td>GET</td>
<td>/employees?name=j</td>
<td>Retrieve employees whose name includes the letter &#8220;j&#8221;</td>
</tr>
<tr>
<td>GET</td>
<td>/employees/3</td>
<td>Retrieve employee with id=3</td>
</tr>
<tr>
<td>GET</td>
<td>/employees/3/reports</td>
<td>Retrieve employees that are direct reports of employee number 3</td>
</tr>
</table>
<div class="woo-sc-box info   ">
In routes/employee.js, the use of res.jsonp() makes the services work for both JSON and JSONP requests. If the request includes a query parameter named “callback”, a JSONP response is returned, otherwise, a regular JSON response is returned.<br />
</div>
<h4>Step 4: Install dependencies (Express Framework and MongoDB driver)</h4>
<p>Open package.json in a code editor and note that the application has two dependencies: the Express framework and the MongoDB driver. To install these dependencies, open a command line (terminal window), cd to the directory where you extracted the source code, and type:</p>
<pre class="brush: bash; light: true; title: ; notranslate">
npm install
</pre>
<h4>Step 5: Start the server</h4>
<p>Make sure MongoDB is started (Step 2 point 6 above) before you start your Node.js server as follows:</p>
<pre class="brush: bash; light: true; title: ; notranslate">
node server.js
</pre>
<h4>Step 6: Testing the API in your Browser</h4>
<ul>
<li>Retrieve all employees
<p><a href="http://localhost:3000/employees">http://localhost:3000/employees</a></p>
</li>
<li>Retrieve all employees whose name includes the letter &#8220;j&#8221;
<p><a href="http://localhost:3000/employees?name=j">http://localhost:3000/employees?name=j</a></p>
</li>
<li>Retrieve employee with id == 1
<p><a href="http://localhost:3000/employees/1">http://localhost:3000/employees/1</a></p>
</li>
<li>Retrieve employees that are direct reports of employee number 1
<p><a href="http://localhost:3000/employees/1/reports">http://localhost:3000/employees/1/reports</a></p>
</li>
</ul>
<h4>Step 7: Test the API with the Employee Directory Client Application</h4>
<ol>
<li>Download the source code for the Employee Directory client application available in <a href="https://github.com/ccoenraets/directory-backbone-bootstrap">this</a> repository.</li>
<li>Unzip the file anywhere on your file system.</li>
<li>Open index.html in your code editor.</li>
<li>Comment out the &#8220;model-in-memory.js&#8221; script, and uncomment the &#8220;model-jsonp.js&#8221; script to use the JSONP adapter that connects to your Node.js server.</li>
<li>Make sure the MongoDB and Node.js servers are started</li>
<li>Open index.html in a Browser and test the application</li>
</ol>
<div class="woo-sc-box note   ">
Because the templates of this application are loaded using XMLHTTPRequest, you will get a cross domain error (Access-Control-Allow-Origin) if you load index.html from the file system (with the file:// protocol). Make sure you load the application from a web server. For example: http://localhost/directory-backbone-bootstrap.<br />
</div>
<h4>Related Post</h4>
<p>Check out <a href="http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/">this post</a> for another Node.js example with a more complete RESTful API including the ability to add, modify and delete items (POST, PUT, and DELETE HTTP methods). </p>
]]></content:encoded>
			<wfw:commentRss>http://coenraets.org/blog/2013/04/implementing-restful-services-with-node-js-and-mongodb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Real Time Web Analytics with Node.js and Socket.IO</title>
		<link>http://coenraets.org/blog/2012/10/real-time-web-analytics-with-node-js-and-socket-io/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=real-time-web-analytics-with-node-js-and-socket-io</link>
		<comments>http://coenraets.org/blog/2012/10/real-time-web-analytics-with-node-js-and-socket-io/#comments</comments>
		<pubDate>Wed, 10 Oct 2012 16:20:53 +0000</pubDate>
		<dc:creator>Christophe Coenraets</dc:creator>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Socket.IO]]></category>

		<guid isPermaLink="false">http://coenraets.org/blog/?p=4236</guid>
		<description><![CDATA[I&#8217;ve always enjoyed building real-time applications. A few years ago, I built the Java back-end for the Tour of California &#8220;Tour Tracker&#8221;, and over the years, I have also been involved in several real-time Trader Desktop projects that I documented in this blog. So I thought it would be nice to explore the process of [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://coenraets.org/blog/wp-content/uploads/2012/10/socketioanalytics.gif"><img src="http://coenraets.org/blog/wp-content/uploads/2012/10/socketioanalytics.gif" alt="" title="socketioanalytics" width="640" height="520" class="aligncenter size-full wp-image-4430" /></a></p>
<p>I&#8217;ve always enjoyed building real-time applications. A few years ago, I built the <a href="http://coenraets.org/blog/2007/02/building-the-back-end-of-the-tour-of-california-tour-tracker-using-flex-data-services/">Java back-end</a> for the Tour of California &#8220;Tour Tracker&#8221;, and over the years, I have also been involved in several real-time Trader Desktop projects that I documented in this blog. So I thought it would be nice to explore the process of building a real-time application with Node.js and Socket.IO.</p>
<p>As an example, we&#8217;ll build a simple web analytics dashboard that shows pages being accessed on a web site in real-time. Kind of like the <a href="http://analytics.blogspot.com/2011/09/whats-happening-on-your-site-right-now.html">real-time view</a> in Google Analytics.</p>
<p>The basic flow of the app is as follows:</p>
<p><a href="http://coenraets.org/blog/wp-content/uploads/2012/10/socketiodiagram.jpg"><img src="http://coenraets.org/blog/wp-content/uploads/2012/10/socketiodiagram.jpg" alt="" title="socketiodiagram" width="428" height="290" class="aligncenter size-full wp-image-4293" /></a><br />
<span id="more-4236"></span></p>
<ol>
<li>The instrumented web application sends a message to the server every time there is a page change within the app.</li>
<li>Upon reception, the server processes the message and&#8230;</li>
<li>&#8230; pushes it to the clients who listen for &#8220;pageview&#8221; messages.</li>
</ol>
<p><br/></p>
<h3>Testing the Hosted Version of the Application</h3>
<p>A live version of the application is hosted on <a href="http://www.heroku.com/">Heroku</a>. </p>
<ol>
<li>Open a browser and access <a href="http://nodecellar.coenraets.org/dashboard.html">http://nodecellar.coenraets.org/dashboard.html</a></li>
<li>Open a different browser window and start the main Node Cellar application: <a href="http://nodecellar.coenraets.org">http://nodecellar.coenraets.org</a></li>
<li>Navigate through the application: the dashboard should display each page view.</li>
</ol>
<p>In the remaining of this article we will go through the steps of building the application from scratch.</p>
<h3>First Iteration: Basic Implementation</h3>
<p>Node.js and Socket.IO make it easy to implement this type of real-time messaging system. Here is a simple (yet fully functional) implementation of the application:</p>
<h4>The Server</h4>
<p><script src="https://gist.github.com/3859582.js?file=server.js"></script><br />
In this first implementation, Node.js doesn&#8217;t serve the application&#8217;s HTML pages. Pages loaded from any domain (or even from the file system) can connect to our message server to send or listen to &#8220;pageview&#8221; messages.</p>
<h4>The Instrumented Web App</h4>
<p>Here is an example of an instrumented page with a script that sends a message to the server every time the page is loaded.<br />
<script src="https://gist.github.com/3859582.js?file=simplepage.html"></script></p>
<p>As mentioned above, this page can be loaded from any domain or from the file system.</p>
<h4>The Real Time Dashboard</h4>
<p>Here is a bare-bones implementation of the real-time dashboard application that receives &#8220;pageview&#8221; messages from the server.<br />
<script src="https://gist.github.com/3859582.js?file=dashboard.html"></script></p>
<p>That&#8217;s basically all you need to start building a sophisticated user interface with real-time charts, counters, maps, etc.</p>
<h4>Testing the Application</h4>
<ol>
<li>Make sure you have Node.js and Socket.IO installed</li>
<li>Start the Node.js server
<p class="shell">node server</p>
</li>
<li>Double-click dashboard.html in Finder (Mac) or Explorer (Windows) to open the page in your default browser.</li>
<li>Double-click simplepage.html in Finder or Explorer to open the page in your default browser (in a separate window).
<li>Refresh simplepage.html repeatedly: the dashboard should display each page view.</li>
</ol>
<p><br/></p>
<h3>Second Iteration: Adding Authorization</h3>
<p>The solution described above works fine, but there are some potential security issues we need to address: </p>
<ol>
<li>Any application (from any domain) can send a message to our server.</li>
<li>Any application (from any domain) can listen to the messages pushed by our server.</li>
</ol>
<p>Let&#8217;s refine our solution to make sure that only authorized clients can connect to our server. Socket.IO provides two different authorization methods: global authorization and namespace authorization (<a href="https://github.com/LearnBoost/socket.io/wiki/Authorizing">more info</a>). In both cases, the <em>handshakeData</em> object provides information (headers, IP address, xdomain, etc) that is useful to implement your authorization logic and determine whether or not you want to allow the client to connect. In this application, we will use global authorization and reject all the cross-domain connection attempts:<br />
<script src="https://gist.github.com/3859430.js?file=authorization.js"></script></p>
<p>There are many other ways you can secure your connections, but that discussion is beyond the scope of this article. </p>
<p>Rejecting cross-domain connections means that the application pages now also have to be served by the Node.js server. To put our new authorization policy into practice, let&#8217;s add the real-time web analytics capability to the Node Cellar application that I shared in my <a href="http://coenraets.org/blog/2012/10/nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb/">previous post</a>. </p>
<h4>The Server</h4>
<p>The server now serves the HTML pages and hosts Socket.IO.<br />
<script src="https://gist.github.com/3859656.js?file=server.js"></script></p>
<h4>The Instrumented Web App</h4>
<p>The following script has been added to index.html to send a &#8220;pageview&#8221; message to the server every time the page changes.<br />
<script src="https://gist.github.com/3859656.js?file=index.html"></script><br />
Notes:</p>
<ul>
<li>We actually don&#8217;t need to use Socket.IO for this part of the application. The client sends a &#8220;pageview&#8221; message to the server and doesn&#8217;t listen for messages from the server. In other words, this is a traditional client-to-server one-way communication that could be implemented with a traditional Ajax request.</li>
<li>The <em>onhashchange</em> event is used because Node Cellar is a &#8220;Single Page Application&#8221;. The entire application runs within a single page (index.html): views are created dynamically at the client-side and injected into or removed from the DOM as you navigate through the application. Only the hash part of the URL changes (without a page refresh) to reflect the current state of the application.</li>
</ul>
<h4>The Real Time Dashboard</h4>
<p>The final version of the dashboard is shown in the screenshot at the top of this post. The Socket.IO code didn&#8217;t change much since our initial implementation. The final code for dashboard.html is available <a href="https://github.com/ccoenraets/nodecellar/blob/master/public/dashboard.html">here</a>.</p>
<h4>Testing the Application</h4>
<ol>
<li>Make sure you have Node.js and Socket.IO installed</li>
<li>Download the source code</li>
<li>Uncomment the Socket.IO related script in the head of public/index.html</li>
<li>Start the Node.js server
<p class="shell">node serverwithanalytics</p>
</li>
<li>Open a browser and access <a href="http://localhost:3000/dashboard.html">http://localhost:3000/dashboard.html</a></li>
<li>Open a different browser window and start the main Node Cellar application : <a href="http://localhost:3000">http://localhost:3000</a></li>
<li>Navigate through the application: the dashboard should display each page view.</li>
</ol>
<h3>Source Code</h3>
<p>I added the real-time analytics feature to the existing <a href="https://github.com/ccoenraets/nodecellar">nodecellar repository</a>. </p>
<ul>
<li>To start the regular server (without analytics), use:
<p class="shell">node server</p>
</li>
<li>To start the server with analytics, uncomment the Socket.IO related script in the head of public/index.html, and use:
<p class="shell">node serverwithanalytics</p>
</li>
</ul>
<h3>Disclaimer</h3>
<p>This is a sample application, not a production application. Some trade-offs were made to keep the code generic, simple and readable.</p>
]]></content:encoded>
			<wfw:commentRss>http://coenraets.org/blog/2012/10/real-time-web-analytics-with-node-js-and-socket-io/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>NodeCellar: Sample Application with Backbone.js, Twitter Bootstrap, Node.js, Express, and MongoDB</title>
		<link>http://coenraets.org/blog/2012/10/nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb</link>
		<comments>http://coenraets.org/blog/2012/10/nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb/#comments</comments>
		<pubDate>Thu, 04 Oct 2012 15:39:03 +0000</pubDate>
		<dc:creator>Christophe Coenraets</dc:creator>
				<category><![CDATA[Backbone.js]]></category>
		<category><![CDATA[Express]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Twitter Bootstrap]]></category>

		<guid isPermaLink="false">http://coenraets.org/blog/?p=4183</guid>
		<description><![CDATA[In my previous post, I shared my recent experience building a RESTful API with Node.js, MongoDB, and Express. In this post, I&#8217;m sharing the client application that uses that RESTful API. The Node Cellar application allows you to manage (retrieve, create, update, delete) the wines in a wine cellar database. The client application is built [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://nodecellar.coenraets.org"><img src="http://coenraets.org/blog/wp-content/uploads/2012/10/nodecellar.gif" alt="" title="nodecellar" width="640" height="463" class="aligncenter size-full wp-image-4197" /></a></p>
<p>In my <a href="http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/">previous post</a>, I shared my recent experience building a RESTful API with <a href="http://nodejs.org">Node.js</a>, <a href="http://www.mongodb.org/">MongoDB</a>, and <a href="http://expressjs.com/">Express</a>.</p>
<p>In this post, I&#8217;m sharing the client application that uses that RESTful API. The Node Cellar application allows you to manage (retrieve, create, update, delete) the wines in a wine cellar database.<br />
<span id="more-4183"></span><br />
The client application is built with <a href="http://backbonejs.org/">Backbone.js</a> and <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a>.</p>
<h4>Run the Application</h4>
<p>You can run the application <a href="http://nodecellar.coenraets.org">here</a>. For obvious reasons, the create, update, delete features have been disabled in this hosted version. </p>
<p>NOTE: <span style="text-decoration: line-through;">Node.js is running on port 3000 on my EC2 Instance.</span> My friend <a href="http://www.jamesward.com/">James Ward</a> convinced me to host the application on their service over at Heroku. It&#8217;s now running on port 80 at <a href="http://nodecellar.coenraets.org">http://nodecellar.coenraets.org</a>. Thanks James!</p>
<p><a href="http://nodecellar.coenraets.org"><img src="http://coenraets.org/blog/wp-content/uploads/2012/10/nodecellar2.gif" alt="" title="nodecellar2" width="640" height="463" class="aligncenter size-full wp-image-4203" /></a></p>
<h4>Server-Side</h4>
<p>The details of the Node.js, MongoDB, and Express implementation are documented in my <a href="http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/">previous post</a>.</p>
<h4>Client-Side</h4>
<p>In this application, Node.js is used to provide the RESTful services that the client application needs to manipulate the data. Node.js is not used to generate HTML/Views at the server-side. Instead, the Views are created dynamically at the client-side using Backbone.js and Underscore.js templates. They are injected into- and removed from the DOM as needed as you navigate through the application. Node Cellar is a &#8220;single page application&#8221;.</p>
<p>This is a Node.js and MongoDB powered version of an application I initially posted <a href="http://coenraets.org/blog/2012/05/single-page-crud-application-with-backbone-js-and-twitter-bootstrap/">here</a> with PHP and Java backends. The original post provides some additional Backbone.js context. This Node.js version also provides an improved user experience with the latest version of Twitter Bootstrap (2.1.1), and a <a href="http://twitter.github.com/bootstrap/scaffolding.html#responsive">responsive</a> layout. It also uses <a href="http://html.adobe.com/edge/webfonts/">Adobe Edge Web Fonts</a>.</p>
<h4>Source Code</h4>
<p>The source code is available in <a href="https://github.com/ccoenraets/nodecellar">this repository</a> on GitHub.</p>
<p><a href="http://nodecellar.coenraets.org"><img src="http://coenraets.org/blog/wp-content/uploads/2012/10/nodecellar3.gif" alt="" title="nodecellar3" width="640" height="463" class="aligncenter size-full wp-image-4204" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://coenraets.org/blog/2012/10/nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb/feed/</wfw:commentRss>
		<slash:comments>71</slash:comments>
		</item>
		<item>
		<title>Creating a REST API using Node.js, Express, and MongoDB</title>
		<link>http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=creating-a-rest-api-using-node-js-express-and-mongodb</link>
		<comments>http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/#comments</comments>
		<pubDate>Tue, 02 Oct 2012 17:03:24 +0000</pubDate>
		<dc:creator>Christophe Coenraets</dc:creator>
				<category><![CDATA[Express]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://coenraets.org/blog/?p=3967</guid>
		<description><![CDATA[I recently used Node.js, Express, and MongoDB to rewrite a RESTful API I had previously written in Java and PHP with MySQL (Java version, PHP version), and I thought I&#8217;d share the experience&#8230; Here is a quick guide showing how to build a RESTful API using Node.js, Express, and MongoDB. Installing Node.js Go to http://nodejs.org, [...]]]></description>
				<content:encoded><![CDATA[<style>
table {
border-collapse:collapse;
width: 100%;
}
th, td {
padding:4px;
border: 1px solid #ddd;
}
</style>
<p><a href="http://coenraets.org/blog/wp-content/uploads/2012/10/nodemango1.jpg"><img src="http://coenraets.org/blog/wp-content/uploads/2012/10/nodemango1.jpg" alt="" title="nodemango" width="600" height="120" class="aligncenter size-full wp-image-4129" /></a><br />
I recently used Node.js, Express, and MongoDB to rewrite a RESTful API I had previously written in Java and PHP with MySQL (<a href="http://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/">Java version</a>, <a href="http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/">PHP version</a>), and I thought I&#8217;d share the experience&#8230; </p>
<p>Here is a quick guide showing how to build a RESTful API using <a href="http://nodejs.org/">Node.js</a>, <a href="http://expressjs.com/">Express</a>, and <a href="http://www.mongodb.org/">MongoDB</a>.</p>
<h3>Installing Node.js</h3>
<ol>
<li>Go to <a href="http://nodejs.org">http://nodejs.org</a>, and click the <em>Install</em> button.</li>
<li>Run the installer that you just downloaded. When the installer completes, a message indicates that <em>Node was installed at /usr/local/bin/node</em> and <em>npm was installed at /usr/local/bin/npm</em>.</li>
</ol>
<p>At this point node.js is ready to use. Let&#8217;s implement the webserver application from the nodejs.org home page. We will use it as a starting point for our project: a RESTful API to access data (retrieve, create, update, delete) in a wine cellar database.<br />
<span id="more-3967"></span></p>
<ol>
<li>Create a folder named <em>nodecellar</em> anywhere on your file system.</li>
<li>In the wincellar folder, create a file named <em>server.js</em>.</li>
<li>Code server.js as follows:
<p><script src="https://gist.github.com/3815873.js?file=server.js"></script>
</li>
</ol>
<p>We are now ready to start the server and test the application:</p>
<ol>
<li>To start the server, open a shell, <em>cd</em> to your nodecellar directory, and start your server as follows:
<p class="shell">node server.js</p>
</li>
<li>To test the application, open a browser and access <a href="http://localhost:3000">http://localhost:3000</a>.</li>
</ol>
<p><br/></p>
<h3>Installing Express</h3>
<p>Express is a lightweight node.js web application framework. It provides the basic HTTP infrastructure that makes it easy to create REST APIs.</p>
<p>To install Express in the nodecellar application:</p>
<ol>
<li>In the nodecellar folder, create a file named <em>package.json</em> defined as follows:
<p><script src="https://gist.github.com/3815974.js?file=package.json"></script></p>
</li>
<li>Open a shell, <em>cd</em> to the nodecellar directory, and execute the following command to install the express module.
<p class="shell">npm install</p>
<p>A <em>node_modules</em> folder is created in the nodecellar folder, and the Express module is installed in a subfolder of node_modules.
</li>
</ol>
<p>Now that Express is installed, we can stub a basic REST API for the nodecellar application: </p>
<ol>
<li>Open server.js and replace its content as follows:
<p><script src="https://gist.github.com/3815974.js?file=server.js"></script>
</li>
<li>Stop (CTRL+C) and restart the server:
<p class="shell">node server</p>
</li>
<li>To test the API, open a browser and access the following URLs:<br />
<table style="margin-top:12px;">
<tr>
<td width="320">Get all the wines in the database:</td>
<td><a href="http://localhost:3000/wines">http://localhost:3000/wines</a></td>
</tr>
<tr>
<td>Get wine with a specific id (for example: 1):</td>
<td><a href="http://localhost:3000/wines/1">http://localhost:3000/wines/1</a></td>
</tr>
</table>
</li>
</ol>
<p><br/></p>
<h3>Using Node.js Modules</h3>
<p>In a large application, things could easily get out of control if we keep adding code to a single JavaScript file (server.js). Let&#8217;s move the wine-related code in a <em>wines</em> module that we then declare as a dependency in server.js.</p>
<ol>
<li>In the nodecellar folder, create a subfolder called <em>routes</em>.</li>
<li>In the routes folder create a file named <em>wines.js</em> and defined as follows:
<p><script src="https://gist.github.com/3816103.js?file=wines.js"></script>
</li>
<li>Modify server.js as follows to delegate the routes implementation to the wines module:
<p><script src="https://gist.github.com/3816103.js?file=server.js"></script>
</li>
<li>Restart the server and test the APIs:<br />
<table style="margin-top:12px;margin-bottom:12px;">
<tr>
<td width="320">Get all the wines in the database:</td>
<td><a href="http://localhost:3000/wines">http://localhost:3000/wines</a></td>
</tr>
<tr>
<td>Get wine with a specific id (for example: 1):</td>
<td><a href="http://localhost:3000/wines/1">http://localhost:3000/wines/1</a></td>
</tr>
</table>
</li>
</ol>
<p>The next step is to replace the placeholder data with actual data from a MongoDB database.<br />
<br/></p>
<h3>Installing MongoDB</h3>
<p>To install MongoDB on your specific platform, refer to the <a href="http://www.mongodb.org/display/DOCS/Quickstart">MongoDB QuickStart</a>. Here are some quick steps to install MongoDB on a Mac:</p>
<ol>
<li>Open a terminal window and type the following command to download the latest release:
<p class="shell">curl http://downloads.mongodb.org/osx/mongodb-osx-x86_64-2.2.0.tgz > ~/Downloads/mongo.tgz</p>
<p>Note: You may need to adjust the version number. 2.2.0 is the latest production version at the time of this writing.
</li>
<li>Extract the files from the mongo.tgz archive:
<p class="shell">
cd ~/Downloads<br />
tar -zxvf mongo.tgz
</p>
</li>
<li>Move the mongo folder to /usr/local (or another folder according to your personal preferences):
<p class="shell">sudo mv -n mongodb-osx-x86_64-2.2.0/ /usr/local/</p>
</li>
<li>(Optional) Create a symbolic link to make it easier to access:
<p class="shell">sudo ln -s /usr/local/mongodb-osx-x86_64-2.2.0 /usr/local/mongodb</p>
</li>
<li>Create a folder for MongoDB&#8217;s data and set the appropriate permissions:
<p class="shell">sudo mkdir -p /data/db<br />
sudo chown `id -u` /data/db</p>
</li>
<li>Start mongodb
<p class="shell">cd /usr/local/mongodb<br />
./bin/mongod</p>
</li>
<li>You can also open the MongoDB Interactive Shell in another terminal window to interact with your database using a command line interface.
<p class="shell">cd /usr/local/mongodb<br />
./bin/mongo</p>
<p>Refer to the <a href="http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell">MongoDB Interactive Shell documentation</a> for more information.
</li>
</ol>
<p><br/></p>
<h3>Installing the MongoDB Driver for Node.js</h3>
<p>There are different solutions offering different levels of abstraction to access MongoDB from Node.js (For example, <a href="http://mongoosejs.com/">Mongoose</a> and <a href="https://github.com/masylum/mongolia">Mongolia</a>). A comparaison of these solutions is beyond the scope of this article. In this, guide we use the <a href="http://www.mongodb.org/display/DOCS/node.JS">native Node.js driver</a>.  </p>
<p>To install the the native Node.js driver, open a terminal window, cd to your nodecellar folder, and execute the following command:</p>
<p class="shell">npm install mongodb</p>
<p><br/></p>
<h3>Implementing the REST API</h3>
<p>The full REST API for the nodecellar application consists of the following methods:</p>
<table style="margin-bottom:24px;">
<tr>
<th>Method</th>
<th>URL</th>
<th>Action</th>
</tr>
<tr>
<td>GET</td>
<td>/wines</td>
<td>Retrieve all wines</td>
</tr>
<tr>
<td>GET</td>
<td>/wines/5069b47aa892630aae000001</td>
<td>Retrieve the wine with the specified _id</td>
</tr>
<tr>
<td>POST</td>
<td>/wines</td>
<td>Add a new wine</td>
</tr>
<tr>
<td>PUT</td>
<td>/wines/5069b47aa892630aae000001</td>
<td>Update wine with the specified _id</td>
</tr>
<tr>
<td>DELETE</td>
<td>/wines/5069b47aa892630aae000001</td>
<td>Delete the wine with the specified _id</td>
</tr>
</table>
<p>To implement all the <em>routes</em> required by the API, modify server.js as follows:<br />
<script src="https://gist.github.com/3819468.js?file=server.js"></script></p>
<p>To provide the data access logic for each route, modify wines.js as follows:<br />
<script src="https://gist.github.com/3819468.js?file=wines.js"></script></p>
<p>Restart the server to test the API.</p>
<p><br/></p>
<h3>Testing the API using cURL</h3>
<p>If you want to test your API before using it in a client application, you can invoke your REST services straight from a browser address bar. For example, you could try:</p>
<ul>
<li><a href="http://localhost:3000/wines">http://localhost:3000/wines</a></li>
</ul>
<p>You will only be able to test your GET services that way. A more versatile solution to test RESTful services is to use <a href="http://curl.haxx.se/">cURL</a>, a command line utility for transferring data with URL syntax.</p>
<p>For example, using cURL, you can test the Wine Cellar API with the following commands:</p>
<ul>
<li>Get all wines:
<p class="shell">
curl -i -X GET http://localhost:3000/wines
</p>
</li>
<li>Get wine with _id value of 5069b47aa892630aae000007 (use a value that exists in your database):
<p class="shell">
curl -i -X GET http://localhost:3000/wines/5069b47aa892630aae000007
</p>
</li>
<li>Delete wine with _id value of 5069b47aa892630aae000007:
<p class="shell">
curl -i -X DELETE http://localhost:3000/wines/5069b47aa892630aae000007
</p>
</li>
<li>Add a new wine:
<p class="shell">
curl -i -X POST -H &apos;Content-Type: application/json&apos; -d &apos;{&quot;name&quot;: &quot;New Wine&quot;, &quot;year&quot;: &quot;2009&quot;}&apos; http://localhost:3000/wines
</p>
</li>
<li>Modify wine with _id value of 5069b47aa892630aae000007:
<p class="shell">
curl -i -X PUT -H &apos;Content-Type: application/json&apos; -d &apos;{&quot;name&quot;: &quot;New Wine&quot;, &quot;year&quot;: &quot;2010&quot;}&apos; http://localhost:3000/wines/5069b47aa892630aae000007
</p>
</li>
</ul>
<p><br/></p>
<h3>Next Steps</h3>
<p>In my next post, I&#8217;ll share a client application that makes use of that API. Update: The &#8220;next post&#8221; is now available <a href="http://coenraets.org/blog/2012/10/nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb/">here</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/feed/</wfw:commentRss>
		<slash:comments>94</slash:comments>
		</item>
	</channel>
</rss>
