Node.js and Express

Getting Started with the MEAN Stack

Randy J. Fortier
randy.fortier@uoit.ca
@randy_fortier

Outline

  • Node.js
    • npm
  • Express
    • Templates
    • Forms
    • Sessions

Node.js and Express

An Introduction to Node.js and Express

MEAN Stack

  • MongoDB
  • Express
  • AngularJS
  • Node.js

Node.js

  • A JavaScript runtime
    • Uses Google's V8 JavaScript engine
    • Intended for network applications
      • Aside from traditional client-side web
      • Most often used for server-side web
    • Non-blocking, asynchronous, event-driven

npm

  • Node Package Manager
    • Package management tool (like apt-get) for Node.js
    • Let's you install plug-ins
      • Globally (available to all applications)
      • Local to this application
    • Package installation
      • Edit package.json, adding dependencies
      • Let npm update package.json as it installs

Starting a New Project

  • Create the package.json file by hand
  • Use the npm command to generate a basic one:

$ npm init
                        

Installing Packages

  • Local install:
    • Packages get downloaded to /node_modules

$ npm install express
                        

Installing Packages

  • Local install:
    • Installs locally, and updates package.json with the dependency

$ npm install --save express
                        

Installing Packages

  • List locally installed packages:

$ npm list
                        

Installing Packages

  • Global install:
    • Gets installed in Node.js working directory

$ npm install -g express
                        

Installing Packages

  • List globally installed packages:

$ npm list -g
                        

Express

  • A web framework for Node.js
  • Node.js requires that you write substantial code:
    • Setting up the web listener
    • Handling mapping of URIs to code (routing)
    • Support for dynamic pages (templating)

Node.js and Express

Writing Code in Node.js/Express

Hello World

  • A very basic Node.js/Express application:

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

app.set('port', process.env.PORT || 3000);

app.get('/', function(request, response) {
	response.send('Hello from Node.js and Express!');
});

app.listen(app.get('port'), function() {
	console.log('Server listening on port ' + app.get('port'));
});
                        

Routing

  • Routing is handled in an event-driven model
    • An incoming request to a specific URI is captured
    • That URI is mapped to a function
    • The function handles the behaviour and/or output
    • It is possible to have multiple handlers for the same URI

Routing

  • The most generate method is use:
    • Handles any HTTP method to any URI

app.use(function(request, response, next) {
	console.log('REQUEST: url = ' + request.url);
	next();
});
                        

request

  • The request argument has properties and functions related to the HTTP request:
    • Incoming parameters
    • Form data

app.get('/hello', function(request, response) {
	response.send('Hello, ' + request.query.name);
});
                        

response

  • The response argument has properties and functions related to the HTTP response:
    • Sending data
    • Sending files
    • Rendering template pages

app.get('/cats', function(request, response) {
	response.sendFile(__dirname + '/cats.html');
});

app.post('/dogs', function(request, response) {
	response.send('Woof woof!');
});
                        

next

  • The next argument is the function for the next handler:
    • You should normally invoke this handler at the end of your handler's code
    • This type of handler is called middleware

app.use(function(request, response, next) {
	console.log('REQUEST: url = ' + request.url);
	next();
});
                        

get

  • The get function only handles HTTP GET requests:
    • These are normally the ones issued by browsers

app.get('/login', function(request, response) {
	response.sendFile(__dirname + '/login.html');
});
                        

post

  • The post function only handles HTTP POST requests:
    • Useful for handling form data
    • This example requires and uses the body-parser plug-in

app.post('/processLogin', function(request, response) {
    if ((request.body.username === 'admin') && 
        (request.body.password === 'opensesame')) {
	   response.send('Thanks for logging in!');    
    }
});
                        

Parameters

  • Node.js/Express allow three different types of parameters:
    • URL-encoded in a GET URL:
      • e.g. http://localhost/hello?name=Randy

app.get('/hello', function(request, response) {
	response.send('Hello, ' + request.query.name);
});
                        

Parameters

  • Node.js/Express allow three different types of parameters:
    • URL-encoded in a GET URL
    • URL-encoded in a POST body:
      • Most useful for processing forms
      • e.g. ?username=admin&password=opensesame

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/processLogin', function(request, response) {
    if ((request.body.username === 'admin') && 
        (request.body.password === 'opensesame')) {
	   response.send('Thanks for logging in!');    
    }
});
                        

Parameters

  • Node.js/Express allow three different types of parameters:
    • URL-encoded in a GET URL
    • URL-encoded in a POST body
    • URI elements in any URI:
      • e.g. http://localhost/users/15

app.get('/users/:userid', function(request, response) {
	response.send('User Id: ' + request.params.userid);
});
                        

Session Tracking

  • Session tracking is a way to keep data about a user as they move between pages

var session = require('express-session');

app.post('/processLogin', function(request, response) {
    // verify the login data
    // ...
    
    // store the username in the session (i.e. log the user in)
    request.session.username = username;
    request.session.save();
});

                        

Node.js and Express

Templating with Jade/Pug

Templating

  • Templating is very common in web development
    • Template: An HTML file with variables and limited functionality
      • You supply the missing values (e.g. profile data)
    • Express supports several templating engines:
      • Pug (formerly named Jade)
      • Handlebars (inspired by Moustache)
      • Hogan
      • Dust

Rendering Templates in Node.js/Express

  • Use the render function of the response object
  • Pass the name of the template (without the extension)
  • Pass an (optional) dictionary containing variable values

app.set('views', __dirname + '/views');
app.set('view engine', 'pug');

app.get('/', function(request, response) {
	response.render('index', {title: 'Index', 
                              description: 'This is the main page', 
                              firstName: 'Sally'});
});
                        

Pug Templates

  • Templates use a variation of HTML (or XML) syntax:
    • Indentation is very important in Pug/Jade

doctype html
html
	head
		title Home Page

		link(rel="stylesheet",
		     href="/style/main.css")

	body
		div(class="container") Welcome to our home page!
                        

Template Inheritance

  • A handy way to reduce boilerplate code
    • parent - provides the layout of the page

doctype
html
	head
		title= title
		
	body
		div(class="container")
			block content
                        

Template Inheritance

  • A handy way to reduce boilerplate code
    • parent - provides the layout of the page
    • child - provides the content for that layout

extends layout
block content
	h1= title
	p This is a filler paragraph for the index page.
                        

Code

  • You can easily include dynamic code into your templates
    • Conditionals:

div(class="collapse navbar-collapse",
    id="bs-example-navbar-collapse-1")
    ul(class="nav navbar-nav navbar-fixed-top")
        if (username && (username !== ''))
            li
                a(href="/profile") Profile
            li
                a(href="/logout") Logout
        else
            li
                a(href="/login") Login
            li
                a(href="/register") Register
                        

Code

  • You can easily include dynamic code into your templates
    • Conditionals
    • Loops:

table(class="table")
    tr
        th SID
        th First Name
        th Last Name
        th GPA
    each student in students
        tr
            td= student.sid
            td= student.firstName
            td= student.lastName
            td= student.gpa
                        

Wrap-Up

  • In this section, we learned about:
    • Node.js
      • npm
    • Express
      • Routing
      • Parameters and form processing
      • Templating with Pug
      • Session tracking