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.
// server.js (Express 3.0)varexpress=require('express');varapp=express();app.configure(function(){app.use(express.static(__dirname+'/public'));// set the static files locationapp.use(express.logger('dev'));// log every request to the consoleapp.use(express.bodyParser());// pull information from html in POSTapp.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.
// server.js (Express 4.0)varexpress=require('express');varmorgan=require('morgan');varbodyParser=require('body-parser');varmethodOverride=require('method-override');varapp=express();app.use(express.static(__dirname+'/public'));// set the static files locationapp.use(morgan('dev'));// log every request to the consoleapp.use(bodyParser.urlencoded({extended:false}));// parse application/x-www-form-urlencodedapp.use(bodyParser.json());// parse application/jsonapp.use(methodOverride());// simulate DELETE and PUTapp.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 });