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

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 »