Skip to main content

Learning Node.js with Richard Astbury Part 2: Serving Angle Brackets

In part 1, ‘Learning node.js with Richard Astbury’ I followed Richard's instructions to create my own node.js web application using Express. Next Richard wrote a blog post with instructions on how to serve static pages and create a template to be used for all pages in the web application.

First Richard describes how to configure Express to serve static web pages from a public directory in the root of the application:

// load the path package
var path = require('path');

// load the express package
var express = require('express');

// create an express application 
var app = express();

// register middleware to serve static pages
app.use(express.static(path.join(__dirname, 'public')));

// handle GET requests at /
app.get('/', function(req, res){

  // respond with plain text
  res.send('hello world');
});

// start listening on Heroku port or port 8080
app.listen(process.env.PORT || 8080);

and then how to create the directory itself:

mkdir public

Richard suggested putting a favicon in the public directory as a test. So I grabbed and renamed the icon from the Naked Element website:

cd public
wget http://nakedelement.co.uk/wp-content/uploads/2015/04/nefavicon1.jpg
mv nefavicon1.jpg  favicon.ico

And then switched back to the root directory to test it.

cd ..
node server.js

I was hoping to see the favicon in the browser tab, but it wasn’t there, so I tried accessing it directly:

http://localhost:8080/favicon.ico

and it was displayed in the client area of the browser. Keen to see it online, I committed to git and then pushed to Heroku:

git add .
git commit -m"Added middleware to server static content."
git push heroku master

Now when I went to the app on Heroku:

https://nakedlogs.herokuapp.com/

it gave me the icon in the browser tab! Result!

Next Richard explains how to install Hogan for server side templating.

npm install hogan-express --save

I remember from Richard’s previous blog post that using --save should add the dependency to package.json. Let’s see:

git status

  modified:  package.json

Well, git certainly thinks it’s been modified. Let’s have a look at the file itself:

{
  "name": "nakedlogs",
  "version": "0.0.0",
  "description": "A remote logging web application",
  "main": "server.js",
  "dependencies": {
    "express": "~4.13.3",
    "hogan-express": "~0.5.2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "Naked Element Ltd.",
  "license": "BSD-2-Clause"
}

Yep, there it is. Next I followed Richard's instructions and registered Hogan with the application so it would serve views:

// create an express application 
var app = express();

// Register middleware to serve views
app.engine('html', require('hogan-express'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.set('layout', 'layout');

// register middleware to serve static pages
app.use(express.static(path.join(__dirname, 'public')));

Richard’s explanation about how it all worked was very clear. Next I created the views folder which would hold the views:

mkdir views

and the file which would serve as the template for all the views in the app:

touch views/layout.html

and then I pasted in Richard’s template:



 
   
    {{title}}  
   
   
 
 
    {{{yield}}}
 


This was just what I’d been looking for. The {{title}} and {{{yield}}} notation showed me exactly where a title for each page would be inserted and then where the content of each page would be rendered. Next I added a simple view that would display the current time:

touch views/time.html


  The time is : {{time}}


and adjusted the get method in server.js to set the title for the view and get the current time to be inserted into the view:

// load the path package
var path = require('path');

// load the express package
var express = require('express');

// create an express application 
var app = express();

// Register middleware to serve views
app.engine('html', require('hogan-express'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.set('layout', 'layout');

// register middleware to serve static pages
app.use(express.static(path.join(__dirname, 'public')));

// handle GET requests at /
app.get('/', function(req, res){
  res.locals.time = new Date();
  res.locals.title = 'the current time';
  res.render('time');
});

// start listening on Heroku port or port 8080
app.listen(process.env.PORT || 8080);

Then I fired up the app:

node server.js

and went to a web browser to see the current time. Bang! There it was.

This is where Richard’s instructions finished, but I know I’m going to want to use lots of features of Bootstrap and JQuery so, I also went on the add the necessary style sheets and JavaScript:



 
   
    {{title}}  
   
   
   
   
   
    
 
 
    {{{yield}}}
 


I also modified time.html to emphasise the bootstrap styling:


 

The time is : {{time}}


When I have time, I’ll be adding a Bootstrap menu bar across the top and possibly a sidebar. This was one of the requirements I had for my app, so I’m really pleased that Richard has shown me how use a single template for all my pages as it will allow me to have the same menu and sidebar on every page.

I’m already looking forward to databases ‘the node way!’

Comments

Popular posts from this blog

Write Your Own Load Balancer: A worked Example

I was out walking with a techie friend of mine I’d not seen for a while and he asked me if I’d written anything recently. I hadn’t, other than an article on data sharing a few months before and I realised I was missing it. Well, not the writing itself, but the end result. In the last few weeks, another friend of mine, John Cricket , has been setting weekly code challenges via linkedin and his new website, https://codingchallenges.fyi/ . They were all quite interesting, but one in particular on writing load balancers appealed, so I thought I’d kill two birds with one stone and write up a worked example. You’ll find my worked example below. The challenge itself is italics and voice is that of John Crickets. The Coding Challenge https://codingchallenges.fyi/challenges/challenge-load-balancer/ Write Your Own Load Balancer This challenge is to build your own application layer load balancer. A load balancer sits in front of a group of servers and routes client requests across all of the serv...

Catalina-Ant for Tomcat 7

I recently upgraded from Tomcat 6 to Tomcat 7 and all of my Ant deployment scripts stopped working. I eventually worked out why and made the necessary changes, but there doesn’t seem to be a complete description of how to use Catalina-Ant for Tomcat 7 on the web so I thought I'd write one. To start with, make sure Tomcat manager is configured for use by Catalina-Ant. Make sure that manager-script is included in the roles for one of the users in TOMCAT_HOME/conf/tomcat-users.xml . For example: <tomcat-users> <user name="admin" password="s3cr£t" roles="manager-gui, manager-script "/> </tomcat-users> Catalina-Ant for Tomcat 6 was encapsulated within a single JAR file. Catalina-Ant for Tomcat 7 requires four JAR files. One from TOMCAT_HOME/bin : tomcat-juli.jar and three from TOMCAT_HOME/lib: catalina-ant.jar tomcat-coyote.jar tomcat-util.jar There are at least three ways of making the JARs available to Ant: Copy the JARs into th...

RESTful Behaviour Guide

I’ve used a lot of existing Representational State Transfer (REST) APIs and have created several of my own. I see a lot of inconsistency, not just between REST APIs but often within a single REST API. I think most developers understand, at a high level, what a REST API is for and how it should work, but lack a detailed understanding. I think the first thing they forget to consider is that REST APIs allow you to identify and manipulate resources on the web. Here I want to look briefly at what a REST API is and offer some advice on how to structure one, how it should behave and what should be considered when building it. I know this isn’t emacs vs vi, but it can be quite contentious. So, as  Barbossa from Pirates of the Caribbean said, this “...is more what you’d call ‘guidelines’ than actual rules.” Resources & Identifiers In their book, Rest in Practice - Hypermedia and Systems Architecture (‎ISBN: 978-0596805821), Jim Webber, Savas Parastatidis and Ian Robinson describe resour...