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 http://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.

Let’s try adding another route…

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

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

app.get('/about', function(request, response) {
   response.send("<h1>About</h1>");
});

app.listen(8124);

If you open a browser and type in http://127.0.0.1:8124/about you should see our different route rendering different markup! Pretty neat, eh?

Of course, right now our application is not all that interesting. It’s just static markup. More importantly, we’re definitely *not* going to want to have HTML in our routes because we are violating the principle of separation of concern by mixing our view logic with our route/controller logic making a nice big plate of spaghetti. To solve this, we’re going to want to use some kind of templating engine so that we can add our markup to an HTML file but also have the file render data that we pass to it. That’s what we’ll look at next.

Templates & Views

Using templates to render different views in JavaScript involves passing data to a file and then using special syntax to render that data to a client — usually a browser Window of some kind. See this discussion on Templates in Backbone.js for a good introduction to JavaScript templating and templating engines. We’re going to do something similar with Express using Handlebars as our templating engine.

To install Handlebars we’re going to want to type the following into our terminal (just as we did before when installing Express)…

$ npm install hbs

And now we can add it as a module…

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

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

app.get('/about', function(request, response) {
   response.send("<h1>About</h1>");
});

app.listen(8124);

More info on the Handlebars module can be found here.

We’re going to want to add a couple of additional lines and make some changes to the code that will tell Express to use HTML templates that we’ll be creating shortly. We’re going to be using HTML files — indicated by the use of the app.set(‘view engine’, ‘html’) line and notice that in our routes instead of using response.send() we’re now using response.render() to render markup using the template…

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

app.set('view engine', 'html');
app.engine('html', hbs.__express);

app.get('/', function(request, response) {
   response.render('index');
});

app.get('/about', function(request, response) {
   response.render('about');
});

app.listen(8124);

By default, Express looks for templates in a “views” folder, so let’s add a “views” directory and create an index.html file in it with the following…

<html>
<head>
<title>Express App</title>
</head>
 
<body>
<h1>Our Express App with Templates</h1>

 
</body>
</html>

We can also create an about.html file and place it in the same “views” folder.

Now if we restart our server and go to the home route, we can see that Express is using this template to render the HTML to the browser. Pretty slick!

Dynamic Templates & Passing Data to Views

Our application is still just rendering static HTML. Let’s change that by figuring out if there is a way that we can pass data to our templates.

Edit the index.html file in our views folder to look like the following…

<html>
<head>
<title>{{title}}</title>
</head>
 
<body>
<h1>{{title}}</h1>

 
</body>
</html>

Now let’s edit our application…

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

app.set('view engine', 'html');
app.engine('html', hbs.__express);

app.get('/', function(request, response) {
   var welcome = 'Our Express App with Templates';
   response.render('index',{title:welcome});
});

app.get('/about', function(request, response) {
   response.render('about');
});

app.listen(8124);

As you can see here, we are now passing data into our index.html template. The text in the title property of the object we pass in is rendered in the {{title}} section by Handlebars.

Let’s do something a bit more complicated. Edit the server file so that it looks like the following.

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

app.set('view engine', 'html');
app.engine('html', hbs.__express);

app.get('/', function(request, response) {
   
   var welcome = 'Our Express App with Templates';
   
   var products = [
       {"id":1, "name":"Apple", "price": 4.99 },
       {"id":2, "name":"Pear", "price": 3.99 },
       {"id":3, "name":"Orange", "price": 5.99 }
   ];
   
   response.render('index', {title: welcome, products: products});
});

app.get('/about', function(request, response) {
   response.render('about');
});

app.listen(8124);

Here in our home route we are getting an array of JSON objects that we’ve defined statically. In a real application you’d connect to some database here or get data from a web service to get the objects that you want to pass to your views.

After this, edit the index.html view to look like the following…

<html>
<head>
<title>{{title}}</title>
</head>
 
<body>
<h1>{{title}}</h1>

{{#each products}}
   <p>
      <a href="/product/{{id}}">{{name}} - {{ price }}</a>
   </p>
{{/each}}
 
</body>
</html>

Now if we go to our home route, we see more dynamic data rendered as output. Here we are using an ((#each}} loop to iterate over the list of products that we passed in.

Let’s add a route for that. Create a /products/:id get route as follows.

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

app.set('view engine', 'html');
app.engine('html', hbs.__express);

app.get('/', function(request, response) {
   
   var welcome = 'Our Express App with Templates';
   
   var products = [
       {"id":1, "name":"Apple", "price": 4.99 },
       {"id":2, "name":"Pear", "price": 3.99 },
       {"id":3, "name":"Orange", "price": 5.99 }
   ];
   
   response.render('index', {title: welcome, products: products});
});

app.get('/about', function(request, response) {
   response.render('about');
});

app.get('/product/:id', function(request, response) {
    var id = request.params.id;
    response.render('product', {title: 'Product #' + id});
});

app.listen(8124);

The :id part at the end indicates that it is a dynamic “id” parameter in the URL query string. As you can see, we can fetch that property out of the request by using request.params.id. Now create a product.html file and place it in our views folder…

<html>
<head>
<title>{{title}}</title>
</head>
 
<body>
<h1>{{title}}</h1>
 
</body>
</html>

Here we are just rendering product #1, #2, etc. In a real application we’d do a name lookup based on the id to get all sorts of information about a specific product for this page and pass it to the view. But it gives you an idea of how you would go about rendering a dynamic page based on the id parameter.

So that concludes our very brief introduction to Express! We have just scratched the surface and there is a lot more to explore. Next steps would include looking at things like POST, PUT, and DELETE routes, database integration, and partial templates… just to name a few. Be sure to check out ExpressJS.com for more information including the API reference and documentation.

9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

0 Responses to Introduction to Express.js

Leave a Reply