Saturday, February 14, 2015

Overview

This post is all about the differences between Express v3 and v4. You can find more information here.

Package.json and server.js

A lot of middleware was removed and placed into their own modules so that they can get worked on without impacting Express. I’ll show you how you used to make an Express server in v3 and how you make one in v4.

Express 3

1
2
3
4
5
6
7
8
// package.json (Express 3.0)
{
  "name": "old-express",
  "main": "server.js",
  "dependencies": {
    "express": "~3.4.8"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
// server.js (Express 3.0)
var express = require('express');
var app     = express();

app.configure(function() {
    app.use(express.static(__dirname + '/public'));   // set the static files location
    app.use(express.logger('dev'));                   // log every request to the console
    app.use(express.bodyParser());                    // pull information from html in POST
    app.use(express.methodOverride());                // simulate DELETE and PUT
});

app.listen(3000);   
console.log('Server started on port 3000');           // notify user

Here’s a list of middleWare that was turned into separate modules.

Express 3.0 Name Express 4.0 Name
bodyParser body-parser
compress compression
cookieSession cookie-session
logger morgan
cookieParser cookie-parser
session express-session
favicon static-favicon
response-time response-time
error-handler errorhandler
method-override method-override
timeout connect-timeout
vhost vhost
csrf csurf

Express 4

1
2
3
4
5
6
7
8
9
10
11
// package.json (Express 4.0)
{
  "name": "new-express",
  "main": "server.js",
  "dependencies": {
    "express": "~4.0.0",
    "morgan": "~1.0.0",
    "body-parser": "~1.0.0",
    "method-override": "~1.0.0"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// server.js (Express 4.0)
var express        = require('express');
var morgan         = require('morgan');
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var app            = express();

app.use(express.static(__dirname + '/public'));     // set the static files location
app.use(morgan('dev'));                             // log every request to the console
app.use(bodyParser.urlencoded({ extended: false }));// parse application/x-www-form-urlencoded
app.use(bodyParser.json());                         // parse application/json
app.use(methodOverride());                          // simulate DELETE and PUT

app.listen(3000);   
console.log('Server started on port 3000');         // shoutout to the user

Routes

Express 3

1
2
3
4
5
6
7
8
// (Express 3.0)
app.get('/dogs', function(req, res, next) {
    // do stuff
});

app.post('/dogs', function(req, res, next) {
    // do stuff 
});

Express 4

1
2
3
4
5
6
7
8
// (Express 4.0)
app.route('/dogs')
    .get(function(req, res, next) {
        // do stuff 
    })
    .post(function(req, res, next) {
        // do stuff 
    });

Random Posts