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

Bloodstock 2009

This year was one of the best Bloodstock s ever, which surprised me as the line up didn't look too strong. I haven't come away with a list of bands I want to buy all the albums of, but I did enjoy a lot of the performances. Insomnium[6] sound a lot like Swallow the Sun and Paradise Lost. They put on a very good show. I find a lot of old thrash bands quite boring, but Sodom[5] were quite good. They could have done with a second guitarist and the bass broke in the first song and it seemed to take ages to get it fixed. Saxon[8] gave us some some classic traditional heavy metal. Solid, as expected. The best bit was, following the guitarist standing on a monitor, Biff Bifford ripped off the sign saying "DO NOT STAND" and showed it to the audience. Once their sound was sorted, Arch Enemy[10] stole the show. They turned out not only to be the best band of the day, but of the festival, but then that's what you'd expect from Arch Enemy. Carcass[4] were very disappoin

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