Share Tweet Reccomend

Creating an MVC Express.js Application

Express.js is probably currently the most popular Node.js framework for building web applications and APIs. It has a good history, a good community around it, lots of modules built for it, and a fairly solid reputation.

In what follows we’re going to walk through how to build an Express.js application using the Model View Controller (MVC) design pattern. It’s likely that we’ll do this tutorial in multiple parts.We’ll start out with a simple application structure and then we’ll move on by adding more complex concepts like authentication, dynamic routing, and reading from and writing to a database.

To start, it’s a good idea to have some background on both Node.js and Express so you know some of the terminology and philosophy behind what is being discussed. If you are not entirely familiar with Express.js there is an introduction to it here. And if you’re not entirely familiar with Node.js there is a primer on Node.js here.

At the time of this writing Express is at version 4.X. If you are reading this at a later point, it’s possible that the latest version differs quite significantly from this. Be sure to check out the Express.js homepage to find information on how to properly set things up using the most current version of Express. However, it may be the case that the steps followed in this tutorial will not be fully compatible with the most recent version of Express.js

package.json

To start we’re going to want to create a package.json file. You can read more about pakcage.json here. package.json will define some metadata type things like the name and version of the application, but most importantly, it will specify what modules you will need to download and run the application. You can read more about modules in Node.js here as well as in any good introduction to Node.js. Express is itself a Node.js module and it makes use of other Node.js modules. Some modules like “http” are core Node.js modules (part of the Node.js core) and some like express.js are third-party. Core Node.js modules will always be available to your application because it is running on Node.js

So our sample package.json file will look like the following…

{
    "name": "MVC-Express-Application",
    "description": "An Express.js application using the MVC design pattern...",
    "version": "0.0.1",
    "dependencies": {
        "express": "4.4.4",		
    }
}

One item of note: the name of any given package cannot have any spaces. This is to ensure that installation of packages is easy and consistent across all environments.If people were ever wanting to install our application as a module on npm (if we ever put our application on npm) by running $ npm install MVC-Express-Application it would not work if the package was named MVC Express Application. If we ran $ npm install MVC Express Application, the CLI would get confused.

Now if we run the following from the directory where our package.json file resides

$ npm install

all of the dependencies that we have specified will be downloaded and installed into a “node_modules” directory. The great thing about this is that if we need to update the versions of our modules or add new ones, we can just add or edit this package.json file and run “npm install” again. The npm installer will figure out all of the files needed. We are limited to the modules we are installing right now, but we will be adding a lot more to this later.

Application

Next we’ll want to create an “app.js” file. This file is the kickoff/entry point of our application when it starts up. This is akin to the main() function you’d find in C++ or Java.

The first components we’re going to want to add are here…

var express = require('express');

This loads up the express module. We can now refer to it in our code.

A lot of the modules we’ll be loading up are part of the Express.js project itself. There are many useful items that our application will be utilizing at various times throughout our application. As is described in the Node.js documentation on modules, Node.js modules can be loaded via references to filenames so long as those filenames are not named the same as reserved core Node.js modules, e.g. the “http” module.

Read More »

Share Tweet Reccomend

Introduction to Ghost

When Ghost first made its appearance on the Internet via some initial videos demonstrating its features and capabilities as a new blogging platform, there was a lot of excitement around it. There was an enthusiastically supported Kickstarter campaign that raised a sizable amount of money. Below is the video showcasing Ghost…

Fast forward to 10/14/2013, Ghost released to the general public today. Will this go down as a day that everyone remembers as a monumental day in history, or are we seeing just a frenzy of brief initial energy? Only time will tell, but Ghost seems to have some unique things going for it. For one, it runs on Node.js. This is something that is unique when compared to other popular blogging platforms and content management systems. To learn more about Node.js you can take a look at the Node.js primer elsewhere on this site. While there are probably some other Node-based blogging platforms that have been written by people in the Node.js community, Ghost definitely seems to have the most visibility at present. I like Node.js and I like blogging so it seems like a coming together of some good things.

Secondly, one of the engaging features Ghost possesses is that in creating a post you can use simple markdown (which is also used on other popular sites such as GitHub and Reddit) to easily bridge the gap between entering plain text into an editor and having it be cleanly converted to HTML. And beyond that there is a slick live editing feature where you can see what your post is going to look like in real-time as you edit. You don’t even have to click any preview button to see what you are creating because it is right there in front of you.

And then lastly, Ghost proclaims to be a return to the basics of being “just a blogging platform”. This is where WordPress got its start before it matured into a full-fledged content management system over the years. It will be interesting to see if Ghost sticks to its roots or if people will try to turn it into all things for all purposes.

In 2013, a lot of people use WordPress for their blogs because it is so ubiquitous across the internet. Ghost is likely going to need to have some significant appealing features that really set it apart from something as established as WordPress before it becomes widely adopted. But there are definitely going to be some initial challenges for Ghost to overcome. One is the learning curve of using and developing on a platform such as Node.js which in 2013 is still an emerging technology. Installation and deployment to production will not immediately be available on all web hosts. Additionally, like any piece of software in its infancy, features will be somewhat limited. At its launch Ghost had no native comments system and only supports one user account per blog. So there are definitely a number of elements across the entire stack that need to bake in the oven a bit longer. But these things will come with time and with enthusiastic community involvement things may come quicker than anticipated.

Overall, Ghost looks promising and the future looks bright… so it is definitely something to keep an eye on as it grows and matures. If you want to go check it out, the Ghost homepage can be found here and the Ghost GitHub page is here.

Share Tweet Reccomend

Express.js Authentication

Now we will discuss how to implement authentication in Express.js. Express.js was discussed previously in the Introduction to Express.js. In the discussion there, we looked at how Express is a web-application framework just like CodeIgniter, Django, or Laravel except instead of running on something like Apache or Ngnix, it runs on Node.js and instead of being written in PHP or Python, it is written in JavaScript. Before looking at the following section, it might be a good idea to be familiar with Express.js by reading the introduction to Express and be familiar with Node.js as well. A Node.js Primer will help you with that.

When you think authentication in web development, you think logging in and logging out. Note that this is a little bit different from authorization, which has more to do with whether a logged in user has the permissions to do a certain action on a website. This the reason that you have different roles such as “Administrator,” “Editor,” and “User” defined within different systems. For this section we’ll focus more on authentication, but a lot of the ways that you handle authentication can also be extended upon to implement authorization.

Session-Based Authentication

When you speak of authentication in modern web applications, there are a number of different implementations you could be talking about. One of the more traditional approaches is the use of sessions. Sessions go back as far as anyone can remember with anything having to do with the web. Express.js supports sessions and you can use them just as you would in other languages like PHP.

Place the following code in a file called server.js. Obviously, in a real application we’d want to separate the markup we’re returning out into views and use a templating language to render them like we did in the introduction to Express. But for now, this will do just to serve for purpose of example…

var express = require('express');
var app = express();

app.use(express.bodyParser());
app.use(express.cookieParser('shhhh, very secret'));
app.use(express.session());


function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error = 'Access denied!';
    res.redirect('/login');
  }
}

app.get('/', function(request, response) {
   response.send('This is the homepage');
});

app.get('/login', function(request, response) {
   response.send('<form method="post" action="/login">' +
  '<p>' +
    '<label>Username:</label>' +
    '<input type="text" name="username">' +
  '</p>' +
  '<p>' +
    '<label>Password:</label>' +
    '<input type="text" name="password">' +
  '</p>' +
  '<p>' +
    '<input type="submit" value="Login">' +
  '</p>' +
  '</form>');
});

app.post('/login', function(request, response) {

    var username = request.body.username;
    var password = request.body.password;

    if(username == 'demo' && password == 'demo'){
        request.session.regenerate(function(){
        request.session.user = username;
        response.redirect('/restricted');
        });
    }
    else {
       res.redirect('login');
    }	
});

app.get('/logout', function(request, response){
    request.session.destroy(function(){
        response.redirect('/');
    });
});

app.get('/restricted', restrict, function(request, response){
  response.send('This is the restricted area! Hello ' + request.session.user + '! click <a href="/logout">here to logout</a>');
});

app.listen(8124, function(){
    console.log('Server running...');
});

Now if you run the following command in the same directory as server.js…

node server

and then open up your browser to https://localhost:8124 you can see the homepage as defined by the default route.

Read More »

Share Tweet Reccomend

Introduction to Express.js

Express is one of the more popular solutions for running a web-server and creating web applications using Node.js. If you are not familiar with Node.js and what it is all about, this primer has an introductory discussion on some of the concepts behind Node.js and some of the potential benefits it offers for certain solutions in certain environments. I highly recommend reading that first before reading what follows if you are not yet acquainted with Node.js. Express is even mentioned a bit in there as well.

Express is a web-application framework just like Django, CodeIgniter, or Laravel. The only difference is that instead of running on something like Apache, it runs on Node.js and instead of being written in PHP or Python, it is written in JavaScript. There are other web application frameworks that run on top of Node.js (like Hapi) but Express is one of the more popular ones.

Below is a link to what we will be building in this section…

Demo Files

Express, like other Node.js installations, comes in the form of a module. You can use a utility called “npm” to install it using the command line. To install Express we just have to type the following into our Node.js command line…

$ npm install express

This will download all of the files that Express requires (dependencies) and will place them in a folder called “node_modules”.

Now that we have Express installed we can get started. Create a file named server.js and add the following…

var express = require('express');
var app = express();

app.get('/', function(request, response) {
   response.send("<h1>Our Express App</h1>");
});

app.listen(8124);

Then open up your favorite terminal (like BASH) and type the following…

$ node server.js

If you open a browser and type in https://127.0.0.1:8124/ you should see the text appear. The great thing about Express is that right out-of-the-box we can use it to define some routes and build an entire web application. If you have used Lavavel or the Slim PHP Framework or something similar this might look familiar. We can also define routes for the other HTTP verbs: POST, PUT, and DELETE. We can return HTML or we can use it to create an API that returns XML or JSON. The possibilities for what we can do with it are all there.

Read More »

Share Tweet Reccomend

A Node.js Primer

Moving into the second decade of the 21st century, if you have been immersed in the web development community — and more specifically, the JavaScript community — in any capacity, then you likely remember hearing something about Node.js discussed somewhere. Maybe you already know all about it, maybe you know a little, or maybe you’re not yet familiar with it. In what follows, we’re going to take a brief look at some of the components of Node.js, what it is, and why people have gotten excited about it.

Node.js Introduction

What is Node.js? Before we get into that, let’s back up a minute and start by talking about web servers. You know about web servers, right? They’re computers that have software running on them that are able to respond to HTTP requests from clients (which most of the time means browsers like Chrome, Firefox, Safari, and Internet Explorer… either desktop or mobile). They’re written in languages like Perl, C, and C++. Then they have other code like Python or PHP that runs on top of them so that when a client connects to a server, all the code runs, works it’s magic (hopefully in a semi-functional way) and returns a web page of HTML to the browser… or if the endpoint is a web service: XML or a JSON payload. This is a pretty standard interaction that occurs billions of times each day across the world. If you do anything on the Internet, you participate in this process most often without even thinking about what is going on behind the scenes in the client-server interaction.

So where does Node.js come into the picture? Basically Node.js is an implementation where, instead of responding to HTTP requests, processing them, and returning web pages using the aforementioned languages, you use JavaScript instead! Node.js becomes a web server written in JavaScript. And it doesn’t just stop there. You can also run Node.js right in your own desktop environment and use utilities to perform file processes and other tasks just as you could do if you were using an installed application that was written in Java or something else. So Node.js could perhaps be better described as “JavaScript running outside of the browser.” Local applications are definitely a very useful component of Node.js, but we’re going to specifically focus on the aspect of using Node.js as a web server. But I’d definitely recommend looking at a number of different utilities available for installation to see if you can use Node.js in your development processes or just as something that makes your life easier in some way.

Read More »