Migrating to Express v4.0.0

The biggest change that comes with Express Version 4.0 is that Connect is no longer a dependency. Additionally, most of Express's (and subsequently Connect's) bundled middleware has been stripped out and moved into individual repositories. This is to help speed up the development and release cycles for both the newly separated middleware modules as well as Express itself. The only middleware that remains is express.static (for convenience). The good news here is that we're no longer required to use Express's (and by proxy Connect's) middleware by default!

The other big change is the way routes work. In previous versions the router was a part of the middleware and the routes were all defined as app. verb (). Now, you can either define a route object per route or just define routes by calling app.route('route').verb(callback). Let's go through the process of modifying our existing code so that it is ready to use Express Version 4.0.

Note

Please note that the remainder of this section is devoted to migrating your code to use Express Version 4.x. The remainder of the book, however, continues to assume that you are using Express Version 3.5.x as the code reflects as such.

Using new middleware

One of the first things we want to do is completely remove Connect and install the new dependencies that will replace Connect. Execute the following command to install the new packages:

$ npm install [email protected] morgan body-parser cookie-parser method-override errorhandler --save

This will not only upgrade your version of Express to 4.0.0 but also include all of the additional middleware we will be using in place of Connect. Some of these packages aren't the most self-explanatory (unfortunately), but you'll see what each is used for in the upcoming section. Your package.json file should now look something like this:

"dependencies": {
  "express": "^4.0.0",
  "morgan": "~1.0.0",
  "body-parser": "~1.0.0",
  "cookie-parser": "~1.0.0",
  "method-override": "~1.0.0",
  "errorhandler": "~1.0.0",
  "express3-handlebars": "^0.5.0"
}

Next, we will want to make some changes to the server/configure.js and server/routes.js files.

server/configure.js

We are going to be changing the way our router behaves a little bit, so we need to make some modifications to how the router is configured (and the order in which it is configured). First, remove the app.use(app.router) line and replace it with the routes.initialize(app) line (that was towards the bottom). In addition, include a second parameter with the routes.initalize(app) line so that it looks like the following:

routes.initialize(app, new express.Router());

We are creating a new express.Router() object and passing it in our routes module as the second parameter.

Next, require each of the new dependencies, including express, and remove Connect (at the top of the server/configure.js file):

var path = require('path'),
    routes = require('./routes'),
    exphbs = require('express3-handlebars'),
    express = require('express'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    morgan = require('morgan'),
    methodOverride = require('method-override'),
    errorHandler = require('errorhandler'),

Replace the middleware that was originally set up to use Connect to use the new modules instead.

Replace the connect.logger middleware with its replacement morgan:

//app.use(connect.logger('dev'));
app.use(morgan('dev'));

Replace the connect.bodyParser, connect.json, and connect.urlencoded middleware with a replacement bodyParser:

// app.use(connect.bodyParser({
//     uploadDir:path.join(__dirname, '../public/upload/temp')
// }));
// app.use(connect.json());
// app.use(connect.urlencoded());
app.use(bodyParser({
    uploadDir:path.join(__dirname, '../public/upload/temp')
}));

Replace the connect.methodOverride middleware with its replacement methodOverride:

// app.use(connect.methodOverride());
app.use(methodOverride());

Replace connect.cookieParser with its replacement cookieParser:

// app.use(connect.cookieParser('some-secret-value-here'));
app.use(cookieParser('some-secret-value-here'));

routes.initialize(app, new express.Router());

Replace connect.static with the built-in express.static replacement middleware:

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

Finally, replace connect.errorHandler with its replacement errorHandler:

if ('development' === app.get('env')) {
    // app.use(connect.errorHandler());
    app.use(errorHandler());
}

Note that each of the original connect middleware was commented out in the preceding code so that you can clearly see what was replaced where. Feel free to actually delete those lines in your own code. The final condensed version of the previous code in server/configure.js should look as follows:

var path = require('path'),
    routes = require('./routes'),
    exphbs = require('express3-handlebars'),
    express = require('express'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    morgan = require('morgan'),
    methodOverride = require('method-override'),
    errorHandler = require('errorhandler'),

module.exports = function(app) {
    app.engine('handlebars', exphbs.create({
        defaultLayout: 'main',
        layoutsDir: app.get('views') + '/layouts',
        partialsDir: [app.get('views') + '/partials']
    }).engine);
    app.set('view engine', 'handlebars'),

    app.use(morgan('dev'));
    app.use(bodyParser({
        uploadDir:path.join(__dirname, '../public/upload/temp')
    }));
    app.use(methodOverride());
    app.use(cookieParser('some-secret-value-here'));
    
    routes.initialize(app, new express.Router());

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

    if ('development' === app.get('env')) {
        app.use(errorHandler());
    }

    return app;
};

server/routes.js

Next, we will rewrite the original routes to use the new express.Router() object. The main change here is that we are accepting a new Router object as a parameter to our initialize() function and using router.verb() instead of app.verb() for each of the routes:

var home = require('../controllers/home'),
    image = require('../controllers/image'),

module.exports.initialize = function(app, router) {
    router.get('/', home.index);
    router.get('/images/:image_id', image.index);
    router.post('/images', image.create);
    router.post('/images/:image_id/like', image.like);
    router.post('/images/:image_id/comment', image.comment);

    app.use('/', router);
};

And that's it! Your app has been successfully migrated from Express 3.5.x to 4.0! Remember, the remainder of this book will continue to use Express 3.5.x, so the completed migration changes wont be reflected in the remaining code we write.

If you want, you can continue to use the Connect middleware framework and save a lot of work during the migration, but I wanted to show you how the new middleware works with Express 4.0.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.221.116