<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Thieves Like Us]]></title><description><![CDATA[Opinions and code. But mostly opinions.]]></description><link>http://brianmajewski.com/</link><generator>Ghost 0.6</generator><lastBuildDate>Mon, 25 May 2026 19:21:05 GMT</lastBuildDate><atom:link href="http://brianmajewski.com/tag/express/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[(Re)Learning Backbone Part 7]]></title><description><![CDATA[<p><em>(Note: The code for this project at this point in our progress can be downloaded from <a href="https://github.com/bmajewski/relearning-backbone">Github</a> at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/e55dbc2be4ab5e8ce883ad7e397654e346f5d135">e55dbc2be4ab5e8ce883ad7e397654e346f5d135</a>)</em></p>

<p><strong>Getting Our Users and Displaying Them</strong></p>

<p>Today, we are going to access our REST backend using Backbone's Collection object and display the results on screen. To do this, we'll add</p>]]></description><link>http://brianmajewski.com/2015/02/22/relearning-backbone-part-7/</link><guid isPermaLink="false">3ac3c9a9-ba7d-48c5-b617-0ff012ec5a4e</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[express]]></category><category><![CDATA[bower]]></category><category><![CDATA[requirejs]]></category><category><![CDATA[datatables]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Sun, 22 Feb 2015 23:13:29 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/photo-1416339684178-3a239570f315.jpeg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/photo-1416339684178-3a239570f315.jpeg" alt="(Re)Learning Backbone Part 7"><p><em>(Note: The code for this project at this point in our progress can be downloaded from <a href="https://github.com/bmajewski/relearning-backbone">Github</a> at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/e55dbc2be4ab5e8ce883ad7e397654e346f5d135">e55dbc2be4ab5e8ce883ad7e397654e346f5d135</a>)</em></p>

<p><strong>Getting Our Users and Displaying Them</strong></p>

<p>Today, we are going to access our REST backend using Backbone's Collection object and display the results on screen. To do this, we'll add a link to our navigation section in the header, create a view to display the results, and update the router to include those results in our page layout.</p>

<p><strong>Navigation</strong></p>

<p>Let's go ahead and update <code>/app/page/header.hbs'</code>. Between the <code>navbar-header</code> div and the <code>navbar-right</code> div, add</p>

<pre><code class="language-markup">&lt;ul class="nav navbar-nav"&gt;  
    &lt;li&gt;&lt;a href="#users"&gt;&lt;span class="fa fa-users"&gt;&lt;/span&gt; Users&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;  
</code></pre>

<p>You'll notice there are some 'fa' classes in there. That's because I added <a href="http://fortawesome.github.io/Font-Awesome/">FontAwesome</a> to the mix. Use <strong>bower</strong> to install it</p>

<pre><code>bower install font-awesome --save  
</code></pre>

<p>then add the CSS to your index page  </p>

<pre><code class="language-markup">&lt;link rel="stylesheet" href="components/font-awesome/css/font-awesome.css"&gt;  
</code></pre>

<p>For our navigation, we used a standard A anchor tag with a URL that mimics our REST API URL. There is no technical need to keep them the same (and in fact they are not - our UI does not expose the <code>/api</code> portion) but keeping them aligned is a useful organizational tool. You should also notice that the URL begins with a hash. Backbone, by default, uses Hash URLs. They are more backwards compatible with older browsers that do not support Push State. Normal URLs are preferred and we'll convert this one later on to take advantage of them.</p>

<p><strong>Creating our Model and Collection</strong></p>

<p>Backbone provides some base objects that we can use to contain our model object (a User) and a collection of them. By giving these objects a URL, they will know how to interact with a standard REST API to retrieve and persist the objects. Let's create them now.</p>

<p><em>/app/users/model.js</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var Backbone = require('backbone');

    return Backbone.Model.extend({
        idAttribute: '_id',
        urlRoot: '/api/users'
    });
});
</code></pre>

<p>Here we are setting two properties, <em>idAttribute</em>, which lets Backbone know to use the MongoDB generated value _id as the id for the object, and <em>urlRoot</em>, which tells it the base URL to use when constructing REST calls.</p>

<p><em>/app/users/collection.js</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var Backbone = require('backbone');
    var Model = require('users/model');

    return Backbone.Collection.extend({
        model: Model,
        url: '/api/users'
    });
});
</code></pre>

<p>Again, we are setting two properties. <em>model</em> is the Backbone model of the objects in the collection - in our case the User model. <em>url</em> is the REST API url to retrieve the collection from.</p>

<p><strong>Displaying The Collection</strong></p>

<p>In my apps, I have two different ways to think about displaying a collection of objects. In cases such as our User collection, it is primarily a tabular display of data. It can show all or a portion of the model's properties, and usually presents actions such as <strong>Edit</strong> or <strong>Delete</strong>. In cases such as these, I don't expect the collection to be changing underneath the user without explicit interaction. </p>

<p>Other collections, however, could be more dynamic. Suppose you are looking at a live stream of tweets that are getting continually updated. Perhaps the collection represent pieces in a game that are getting moved around based on rules. In cases like that, we will want to construct a collection view that delegates a lot of control to individual model views and can respond to events that they generate. </p>

<p>For <strong>CRUD</strong> screens like the one we are going to build, we can use the <a href="http://datatables.net/">DataTables</a> library to easily add features like sorting, pagination, and filtering to our view.</p>

<p>Install DataTables and a convenient plugin to mix it in with our Bootstrap theme:</p>

<pre><code>bower install datatables datatables-bootstrap3-plugin --save  
</code></pre>

<p>update <code>require-main.js</code> with the following entries</p>

<pre><code class="language-javascript">"datatables": "../components/datatables/media/js/jquery.dataTables",
"datatables-bootstrap3": 
    "../components/datatables-bootstrap3-plugin/media/js/datatables-bootstrap3"
</code></pre>

<p>and add the CSS to <code>index.html</code></p>

<pre><code class="language-markup">    &lt;link rel="stylesheet" href="components/datatables-bootstrap3-plugin/media/css/datatables-bootstrap3.css"&gt;
</code></pre>

<p>Now let's create our template and view</p>

<p><em>/app/users/list.hbs</em>  </p>

<pre><code class="language-markup">&lt;div class="well"&gt;  
    &lt;h4&gt;&lt;b&gt;Users&lt;/b&gt;&lt;/h4&gt;
&lt;/div&gt;  
&lt;table class="table table-bordered table-striped"&gt;  
    &lt;thead&gt;
    &lt;th&gt;ID&lt;/th&gt;
    &lt;th&gt;Email&lt;/th&gt;
    &lt;th&gt;Name&lt;/th&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
    {{#each users}}
        &lt;tr&gt;
            &lt;td&gt;{{_id}}&lt;/td&gt;
            &lt;td&gt;{{email}}&lt;/td&gt;
            &lt;td&gt;{{name}}&lt;/td&gt;
        &lt;/tr&gt;
    {{/each}}
    &lt;/tbody&gt;
&lt;/table&gt;  
</code></pre>

<p>A fairly straightforward table template. We'll use Handlebars #each directive to loop over the users and display a row for each.</p>

<p><em>/app/users/listView.js</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var Backbone = require('backbone');
    var template = require('hbs!users/list');
    require('datatables');
    require('datatables-bootstrap3');

    return Backbone.View.extend({
        el: '#content',
        render: function(){
            this.$el.html(template({users: this.collection.toJSON()}));
            this.$('table').DataTable();
            return this;
        }
    });

});
</code></pre>

<p>Some differences to call out. We've required our <em>DataTables</em> related libraries but did not assign them to a variable. Since they are plugins to jQuery, we won't need to access them on their own.</p>

<p>In our render method, we take our collection of users, convert them to JSON and pass that in as <em>users</em> to our template to render. This is the object that the #each directive is looping on in our template.</p>

<p>Finally, we activate the <em>DataTables</em> functionality by attaching it to the table in our view.</p>

<p>The only thing that may not be clear is where the collection we convert to JSON is coming from since we did not define it in this view. We could have instantiated it here, and asked it to fetch itself. We would then have to coordinate with our Page view to tell it that the collection was ready, and to rerender it. In some cases, such as when many different backend calls will need to be made to display a page, this will be an appropriate solution. For this simple case, we'll have the router grab the collection and prepare the view before we hand it off to the main Page. This way, it will be ready to render right away. Let's take a look at that:</p>

<p><em>/app/router.js</em>  </p>

<pre><code class="language-javascript">routes: {  
    '': 'home',
    'home': 'home',
    'users': 'users'
},

users: function() {  
    console.log('routing - users');
    require(['users/collection', 'users/listView'], function(Collection, View) {
        var collection = new Collection();
        collection.fetch().done(function(){
            mediator.trigger('page:displayView', new View({collection: collection}));
        });
    });
},
</code></pre>

<p>We've added a route for <code>users</code> that is handled by a <code>users</code> method and the <code>users</code> method itself. We require the users view and collection. We instantiate the collection and fetch the contents. When the contents are retrieved we add them a new view and send a message off to the page to render the view.</p>

<p><strong>Next Steps</strong></p>

<p>In the next installment, we'll some actions to add, edit, and delete users.</p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 4]]></title><description><![CDATA[<p><em>(Note: The code for this series is available on <a href="https://github.com/bmajewski/relearning-backbone">Github</a> - To get the code in preparation for this installment, checkout commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/d82adb485a608278b2003415cab536503c40d5d2">d82adb485a608278b2003415cab536503c40d5d2</a>)</em></p>

<p><strong>Database Integration</strong></p>

<p>A lot of tutorials wave their hands at this point and assume you have a database connected. Worse, some will have you write stubs and</p>]]></description><link>http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/</link><guid isPermaLink="false">6735c52a-db17-41c0-a71f-1fe0a8ccfa47</guid><category><![CDATA[javascript]]></category><category><![CDATA[mongodb]]></category><category><![CDATA[node]]></category><category><![CDATA[express]]></category><category><![CDATA[mongoose]]></category><category><![CDATA[postman]]></category><category><![CDATA[crud]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Fri, 20 Feb 2015 04:17:04 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/Mongoose_-PSF-.png" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/Mongoose_-PSF-.png" alt="(Re)Learning Backbone Part 4"><p><em>(Note: The code for this series is available on <a href="https://github.com/bmajewski/relearning-backbone">Github</a> - To get the code in preparation for this installment, checkout commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/d82adb485a608278b2003415cab536503c40d5d2">d82adb485a608278b2003415cab536503c40d5d2</a>)</em></p>

<p><strong>Database Integration</strong></p>

<p>A lot of tutorials wave their hands at this point and assume you have a database connected. Worse, some will have you write stubs and timeouts to simulate connection delays. If you know what you're doing, these can be a quick way to get a screen or feature running. If you're building from the ground up, you're just delaying the inevitable. Plus, if you've never done it before, figuring out how to wire it in later can be a challenge.</p>

<p><strong>MongoDB and mongoose</strong></p>

<p>Earlier in this series we installed <a href="http://www.mongodb.org/">MongoDB</a>. Ensure that you have a running copy before continuing. For a GUI front end, I like using <a href="https://github.com/jeromelebel/MongoHub-Mac">MongoHub</a>. <a href="http://mongoosejs.com/">Mongoose</a> is an object modeling solution that lets you write simple schema based objects to work between your Node server and your Mongo database. It has hooks for validation, query building and more, and with a healthy plugin ecosystem can do nearly anything you throw at it. We'll only scratch the surface of its feature set.</p>

<p>To install mongoose, run:</p>

<pre><code>npm install mongoose --save  
</code></pre>

<p>We'll need to tell our app how to connect to MongoDB. In our <code>server.js</code> file, add  </p>

<pre><code>var mongoose = require('mongoose');  
</code></pre>

<p>to the dependencies section at the top. Then underneath that, add  </p>

<pre><code>mongoose.connect('mongodb://localhost:27017/rlbb');  
</code></pre>

<p>If you configured MongoDB to run on another port, edit the above the string. <code>rlbb</code> is the name of our database and will be created if not present. Here is also where we would add things like database username, password, and the like if we had them.</p>

<p>Now, let's create a User model. Under <code>app/models</code>, create <code>user.js</code></p>

<pre><code class="language-javascript">var mongoose = require('mongoose');  
var Schema = mongoose.Schema;

var UserSchema = new Schema({  
    name: String,
    email: {type: String, required: true, index: {unique: true}},
    password: {type: String, required: true, select: false}
});

module.exports = mongoose.model('User', UserSchema);  
</code></pre>

<p>Here, we've pulled in our mongoose dependency and created a User Schema object. Mongoose uses the Schema as representation of a MongoDB collection and the base of its functionality. We've defined a <strong>name</strong>, an <strong>email</strong>, and a <strong>password</strong>. Along with the property names, we've defined their <em>SchemaType</em>, in this case, they are all Strings. For email and password, we've also included some additional properties. <em>required</em> indicates that the field must be present to be valid. Other validators include <em>min</em>, <em>max</em>, <em>match</em>, and custom validators can be created. For email, which we will use as our username, we create an index for it, and put a <em>unique</em> constraint on it. For password, we indicate that normal retrieval of this object from the collection should <em>not</em> include the password field. This prevents it from going across the network. When we add authentication later, we will explicitly ask for the password. Finally, we create a mongoose model from the schema and export it.</p>

<p><strong>Our First REST Endpoints</strong></p>

<p>So, we have a model of our User data. We now need a way to retrieve it from and write it to the database. In this app, all of our API URLs will start with <code>/api/</code> and then follow with the appropriate REST endpoints. For user, we will end up creating:  </p>

<dl>  
    <dt>/api/users</dt>
    <dd>POST - With a POST request, a new user will be created.<br>
    GET - With a GET request, this will return all users.
    </dd>

    <dt>/api/users/:user_id</dt>
    <dd>GET - With a GET request, this will return a single user with an ID that matches <i>:user_id</i>.<br>
    PUT - With a PUT request, the user indicated will be updated.<br>
    DELETE - With a DELETE request, the user indicated will be deleted.</dd>
</dl>

<p>With just two endpoints, and using the HTTP verbs, we can satisfy our basic CRUD requirements. To define these, we will create an Express router and then have Express <em>use</em> it, much like we did with the static assets directory and the catch all request handler.</p>

<p>Under <code>app/routes</code>, create <code>user.js</code> <sup id="fnref:1"><a href="http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/#fn:1" rel="footnote">1</a></sup>.</p>

<pre><code class="language-javascript">var bodyParser = require('body-parser');  
var User = require('../models/user');

module.exports = function (app, express) {  
    var userRouter = express.Router();

    userRouter.get('/', function (req, res) {
        res.json({message: 'api is loaded'});
    });

    userRouter.route('/users')
        .post(function (req, res) {
            var user = new User();
            user.name = req.body.name;
            user.username = req.body.username;
            user.password = req.body.password;

            user.save(function (err) {
                if (err) {
                    if (err.code === 11000) {
                        return res.json({success: false, message: 'Duplicate username.'});
                    } else {
                        return res.send(err);
                    }
                } else {
                    res.json({message: 'user created'});
                }

            });
        })
        .get(function (req, res) {
            User.find(function (err, users) {
                if (err) {
                    res.send(err);
                }
                res.json(users);
            })
        });

    userRouter.route('/users/:user_id')
        .get(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);
                res.json(user);
            })
        })
        .put(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);

                if (req.body.name) user.name = req.body.name;
                if (req.body.email) user.email = req.body.email;
                if (req.body.password) user.password = req.body.password;

                user.save(function (err) {
                    if (err)res.send(err);
                    res.json({message: 'user updated'});
                });
            });
        })
        .delete(function (req, res) {
            User.remove({_id: req.params.user_id}, function (err, user) {
                if (err) res.send(err);
                res.json({message: 'user deleted'});
            })
        });

    return userRouter;
};
</code></pre>

<p>This looks like a lot, but it's fairly straightforward. Let's tackle it a chunk at a time.</p>

<pre><code class="language-javascript">var bodyParser = require('body-parser');  
var User = require('../models/user');  
</code></pre>

<p>Here will pull in our dependencies. We will use <em>body-parser</em> to get the data that comes with the PUT and POST requests and <em>User</em> is the user model we just created.</p>

<pre><code class="language-javascript">    var userRouter = express.Router();

    userRouter.get('/', function (req, res) {
        res.json({message: 'api is loaded'});
    });
</code></pre>

<p>Here we create an instance of an Express router. To give us a way to verify our routes have been initialized properly, we create a default route <code>api/</code> that will respond with a canned message. If there are problems we can use this to see if it is a server or database issue.</p>

<pre><code class="language-javascript">userRouter.route('/users')  
        .post(function (req, res) {
            var user = new User();
            user.name = req.body.name;
            user.email = req.body.email;
            user.password = req.body.password;

            user.save(function (err) {
                if (err) {
                    if (err.code === 11000) {
                        return res.json({success: false, message: 'Duplicate username.'});
                    } else {
                        return res.send(err);
                    }
                } else {
                    res.json({message: 'user created'});
                }

            });
        })
        .get(function (req, res) {
            User.find(function (err, users) {
                if (err) {
                    res.send(err);
                }
                res.json(users);
            })
        });
</code></pre>

<p>Here we create the <code>api/users</code> route and handle both the POST and the GET cases. In the POST block, we create a new User, set the fields with data from the request body, and save it. Mongoose handles the heavy lifting of creating the query and talking to the database. We perform some basic error-handling, and return an appropriate message to the client.</p>

<p>In the GET block, we call a static model method on User to retrieve all the stored users and return them. Once again, mongoose takes care of the details.</p>

<pre><code class="language-javascript">userRouter.route('/users/:user_id')  
        .get(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);
                res.json(user);
            })
        })
        .put(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);

                if (req.body.name) user.name = req.body.name;
                if (req.body.username) user.username = req.body.username;
                if (req.body.password) user.password = req.body.password;

                user.save(function (err) {
                    if (err)res.send(err);
                    res.json({message: 'user updated'});
                });
            });
        })
        .delete(function (req, res) {
            User.remove({_id: req.params.user_id}, function (err, user) {
                if (err) res.send(err);
                res.json({message: 'user deleted'});
            })
        });
</code></pre>

<p>Here we create the <code>api/users/:user_id</code> route. Express will take the value in the request that maps to the <code>:user_id</code> section and create a request parameter that we can use. In the GET block, we use mongoose's <em>findById</em> method to retrieve a specific user. In the PUT block, we again retrieve the requested user, update its information with data from the request body, then save it. Finally, in the DELETE block, we use mongoose's <em>remove</em> function to delete the specified user.</p>

<p>Now it's time to wire the router into the server. In <code>server.js</code>, <strong>after</strong> the static directory declaration, add the following</p>

<pre><code class="language-javascript">// already in our file
app.use(express.static(__dirname + '/public'));

// ADD THESE TWO LINES
var userRoutes = require('./app/routes/user')(app, express);  
app.use('/api', userRoutes);

// already in our file
app.get('*', function(req,res){  
    res.sendFile(path.join(__dirname + '/public/index.html'));
});
</code></pre>

<p>First we create the routes, by requiring the file and passing it the two needed fields, app and express. (Go back and look at how we declared our router definition and you will see we have these two params listed). Then, we tell our server to <em>use</em> the routes. Remember, order is important. First our static files, then our API routes, and finally the catch all to serve up our home page. If we added our routes after the catch all, they would never be hit.</p>

<p>If we were to run our server now, with <code>nodemon server.js</code> we would be able to get and set users via HTTP. But... we don't have any users yet, and we don't have screens to input data. Any easy solution is to use something like <a href="https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm/related?hl=en">Postman - REST Client for Chrome</a> (all the browsers have similar tools). In the URL field, enter <code>localhost:1337/api</code> and make sure GET is selected in the dropdown. When you hit send, you should see our test message returned in JSON format. </p>

<p>We can do a similar task to add a user. Set the URL to <code>localhost:1337/api/users</code>, the method to POST, select <code>raw</code> for our input data and add</p>

<pre><code>{ "email" : "hireme@brianmajewski.com", name: "Brian M", password: "123456Secure!"}
</code></pre>

<p>These are the fields we defined on our User model.</p>

<p>We also need to set our content type, so select Headers, and for name put <code>Content-Type</code> and value put <code>application/json</code>. If we're configured right, you should get a response back saying user created. To see our new user, hit the same URL, with GET, and you should receive a response similar to</p>

<pre><code>[
    {
        "_id": "54e6b162eb2ac61c54e9b80f",
        "email": "hireme@brianmajewski.com",
        "name": "Brian M",
        "__v": 0
    }
]
</code></pre>

<p>Notice: Our password is not returned, as we specified in our schema. Experiment with the other routes and verify that you can update and delete users as well.</p>

<p>So there you have the basics for all CRUD operations for your app. Whether you are storing Widgets, Gizmos, Comments, or Reviews, you will follow the same basic pattern. Later, when we add authentication, you'll see how we can enhance mongoose's standard methods to perform extra functionality, such as encrypting the password, before saving the user.</p>

<p>To get the code with these updates checkout commit <a href="https://github.com/bmajewski/relearning-backbone/commit/18b0d51ee45d966abf9293be9a5fe25c6af8c6a6">18b0d51ee45d966abf9293be9a5fe25c6af8c6a6</a></p>

<p><strong>Next Steps</strong></p>

<p>With a functional backend in place, we will begin to create our front end web application. We'll look at using Bower to manage dependencies and RequireJS to load modules.</p>

<p>(<strong>UPDATE</strong>: There was a bug in the PUT block of the /users/:user_id route - <em>username</em> should have been <em>email</em> - This bug was fixed in the Chapter 7 version of the code on Github and in the text above)</p>

<div class="footnotes"><ol>  
    <li class="footnote" id="fn:1">
        <p>Some people prefer to include the function in the name, such as userModel.js and userRoute.js. I go back and forth on this. They are namespaced by their directory structure, so if there is no chance I am going to get them confused, I'll shorten them like I did here. You can name them mickey, pluto, and goofy if that floats your boat. I prefer frameworks without magic naming conventions.<a href="http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/#fnref:1" title="return to article"> ↩</a></p><p>
    </p></li>
    </ol></div>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 3]]></title><description><![CDATA[<p><strong>Project Structure</strong></p>

<p>We are going to start with a simple barebones structure to start with. In your project directory create both an <code>app</code> and a <code>public</code> directory. Under, <code>public</code>, create <code>assets</code>. And we're done. We'll add more as we flesh out the app. I like working iteratively, adding what we</p>]]></description><link>http://brianmajewski.com/2015/02/15/relearning-backbone-part-3/</link><guid isPermaLink="false">d22b402c-21a2-4fb1-81a8-25b81e6e0c73</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[node]]></category><category><![CDATA[npm]]></category><category><![CDATA[express]]></category><category><![CDATA[nodemon]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Sun, 15 Feb 2015 20:30:19 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/p1010298--2-.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/p1010298--2-.jpg" alt="(Re)Learning Backbone Part 3"><p><strong>Project Structure</strong></p>

<p>We are going to start with a simple barebones structure to start with. In your project directory create both an <code>app</code> and a <code>public</code> directory. Under, <code>public</code>, create <code>assets</code>. And we're done. We'll add more as we flesh out the app. I like working iteratively, adding what we need when we need it. Remember, it's <em>software</em> - we can change it if we want to.</p>

<p><img src="http://brianmajewski.com/content/images/2015/02/Screen-Shot-2015-02-15-at-11-38-14-AM.png" alt="(Re)Learning Backbone Part 3"></p>

<p><strong>NPM (Node Package Manager)</strong></p>

<p>To manage our server side dependencies, we are going to use Node's built-in package manager <a href="https://www.npmjs.com/">NPM</a>. To start, we need a <code>package.json</code> file. You can read the docs and create one by hand or you can use the tool to create one. Run  </p>

<pre><code>npm init</code></pre>

<p>in the root of your project, answer the questions, <em>et voila</em>, you should have a <code>package.json</code> file that looks something like this:</p>

<p><img src="http://brianmajewski.com/content/images/2015/02/Screen-Shot-2015-02-15-at-11-48-58-AM.png" alt="(Re)Learning Backbone Part 3"></p>

<p>If you entered something other than <code>server.js</code> for the <em>main</em> value (and you probably did, since it isn't the default), go ahead and edit the contents. <code>server.js</code> will be the main file we run to launch our web server and serve up data.</p>

<p>For our barebones server, we are going to use the following node packages: <a href="http://expressjs.com/">express</a>, <a href="https://www.npmjs.com/package/body-parser">body-parser</a>, <a href="https://www.npmjs.com/package/morgan">morgan</a>, and live</p>

<dl>  
<dt>express</dt>  
<dd>will provide nearly all of the web server functionality along with the middleware we will need to do authentication.</dd>  
<dt>body-parser</dt>  
<dd>will allow us to read json from incoming request</dd>  
<dt>morgan</dt>  
<dd>will let us log incoming requests</dd>  
</dl>

<p>Learning how to use Express would be a lesson in itself and you should dig into their documentation as needed.</p>

<p>To install these, run  </p>

<pre><code>npm install express body-parser morgan --save</code></pre>

<p>from your project root. It will download the packages, and their dependencies, and save the information to your package.json file.</p>

<p>One last package we want to download is <a href="https://www.npmjs.com/package/nodemon">nodemon</a>. When our server is running, this will watch for any changes and restart the server automatically as needed. We need to install this globally, so run:</p>

<pre><code>npm install -g nodemon</code></pre>

<p><strong>server.js</strong></p>

<p>This will be the heart of our web server.</p>

<pre><code class="language-javascript">var express = require('express');  
var bodyParser = require('body-parser');  
var morgan = require('morgan');

var path = require('path');

var app = express();

// Sets us up to read body content from POST requests
app.use(bodyParser.urlencoded({extended: true}));  
app.use(bodyParser.json());

// Adds request logging
app.use(morgan('dev'));

// Sets up the server to serve static files from the public directory
app.use(express.static(__dirname + '/public'));

// For all requests we do not explicitly handle (*), return index.html
app.get('*', function(req,res){  
    res.sendFile(path.join(__dirname + '/public/index.html'));
});


// Listen on port 1337
var port = 1337;  
app.listen(port);  
console.log('Server up and running on port ' + port);  
</code></pre>

<p>So, what's going on here? </p>

<ul>
<li>First we define our dependencies and create an <code>app</code> variable to represent the application/server.</li>
<li>Then, we use the <em>body-parser</em> package to tell our app how to get JSON from the body of incoming requests. </li>
<li>We activate <em>morgan</em> in dev mode, which will log our requests.</li>
<li>We define a directory to serve up static resources like html, css, fonts, etc. <code>__dirname</code> is provided by the <em>path</em> package.</li>
<li>Finally, for all incoming requests that have not been handled yet(<code>*</code>), we return <code>index.html</code>. So, if we ask for a specific CSS file, the static instruction above will handle it. If we ask for an HTML page that doesn't exist, this instruction will handle it. We will be adding more routes and instructions as we go on. As you can see, the order in which we define these routes is important. Express will go through each one until it comes to a handler that satisifes the request. This is a classic implementation of the <a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility</a> pattern.</li>
</ul>

<p>That's it. That's all you need to have a basic web server. We could have left out the body-parser section for an even leaner file, but we will need it next. Run  </p>

<pre><code>nodemon server.js</code></pre>

<p>and you should see output similar to: <br>
<img src="http://brianmajewski.com/content/images/2015/02/Screen-Shot-2015-02-15-at-12-19-18-PM.png" alt="(Re)Learning Backbone Part 3"></p>

<p>We can create a simple <code>index.html</code> file in our public directory and view it in a browser. To ensure that static files are being served up as well, create a <code>css</code> folder under <code>assets</code> and add a <code>styles.css</code> file.</p>

<p><em>Sample HTML</em>  </p>

<pre><code class="language-markup">&lt;!DOCTYPE html&gt;  
&lt;html&gt;  
&lt;head lang="en"&gt;  
    &lt;base href="/"&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Relearning Backbone&lt;/title&gt;
    &lt;link rel="stylesheet" href="assets/css/styles.css"&gt;
&lt;/head&gt;  
&lt;body&gt;  
&lt;h3&gt;Relearning Backbone&lt;/h3&gt;  
&lt;/body&gt;  
&lt;/html&gt;  
</code></pre>

<p><em>Sample CSS</em>  </p>

<pre><code class="language-css">h3 {  
    color: #4169e1;
}
</code></pre>

<p><strong>Next Steps</strong></p>

<p>Next time, we are going to add a database connection to the server, and some User entities to it.</p>]]></content:encoded></item></channel></rss>