Introduction to Express.js 4

Jaakko Salonen

Senior Software Engineer @ Gofore

Overview

Express.js

  • Express Web application framework for node
  • Minimal and flexible; suitable for building regular multi-page applications as well as single-page applications
  • Middleware based design
  • Unopinionated; configure and complement with other libraries to build a full stack

Maturity

  • Was probably the first decent web framework node and has been building audience since
  • Github: ~12k Stars, ~2.5k forks
  • Currently in 4.x series
  • Is actively used in production

Related frameworks

  • Inspired by Sinatra, which shows in design
  • Until 4.x series Express dependend on Connect for its middleware layer
  • Koa: an alternatively next generation web framework from the team that built express (heavily based on ES6 generators)
  • hapi: a configuration-centric server framework that started its life on top of express.

MEAN

  • MEAN = Mongoose Express Angular Node
  • A stack in which Express is commonly used
  • Also available as a framework (mean.io)

Getting Started

Install prerequisites and create project

  • Install node and npm
  • mkdir project && cd project
  • npm init
  • npm install --save express>=4

Simple Application ("app.js")

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

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);

→ node app.js

express-generator

Applications can also be generated with `express-generator` obtainable with:

npm install -g express-generator

Example: scaffold express application with Jade templating and LESS styles:

express --css less myapp

Just install dependencies:

cd myapp
npm install

And run:

npm start

Routing

Defining routes

Directly via VERB methods on application and route objects:

app.VERB(path, [callback...], callback)

router.VERB(path, [callback...], callback)


Or via route objects (recommended approach):

router.route(path)

app.route(path)

Example (recommended approach)

app.route('/profile')
  .all(function(req, res, next) {
    // Runs on all HTTP verbs
  })
  .get(function(req, res, next) {
    res.send('GET called');
  })
  .post(function(req, res, next) {
    res.send('POST called');
  });

Parameters

Named parameters can be assigned to routes and can be accessed from req.params:

router.get('/:user', function(req, res) {
  res.send("Resource for user " + req.params.user);
});

Parameters with custom logic

Custom logic can be added to named parameters.

Say we want to retrieve user resource instead of returning ID:

router.param('user', function(req, res, next, id) {
  req.user = {
    "id": req.params.user,
    "name": "John Doe",
  };
  next();
});

req gets decorated with user object

Note: since the callback returns only after you call next you can do asynchronous operations here too (like fetch user object from database)

Using Middleware

Middleware

  • Middleware ~= global filters that are applied on every request before sending it to the router
  • Earlier version of Express used Connect as the Middleware layer, but this is no longer the case in Express 4.x
  • Middleware available as separate components: see github.com/senchalabs/connect#middleware

static

The only Middleware that is bundled with express.

Example - serve static files from public folder:

app.use(express.static(path.join(__dirname, 'public')));

body-parser

  • Example of a typically used Middleware
  • Parses urlencoded and json bodies to JavaScript objects

Usage example:

app.use(bodyParser());
router.put('/users/:userid', function(req, res) {
  // parsed request body can be accessed now from req.body
});

Ordering

Middleware components are applied in their binding order. Practical example:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

Creating Responses

Response

Response object available via `res` parameter

Documentation for methods: http://expressjs.com/4x/api.html#res.status

Send response

Send with HTTP 200 OK:

res.send('

Hello World

');

JavaScript objects passed as body are sent as JSON:

res.send({id: '1', username: 'johndoe', name: 'John Doe'});

Optionally pass integer as first argument to change status code:

res.send(404);
res.send(500, "Server rror");

Response header fields

Via setters / getters (case-insensitive):

res.set('Content-type', 'text/plain');
var contentType = res.get('Content-type');

Redirect and Location

Redirect with HTTP 302 Found:

res.redirect('/pages/example1');

Redirect with custom HTTP status code:

res.redirect(301, 'http://www.example.com/')

Shorthand for setting Location header:

res.location('/login');

End of Story

Further reading