Middleware In Express: Node.js


We’ve been using middlewares in our previous video tutorials. Today, we’ll have a look at these middlewares.

middleware-connect-express-nodejs

Connect is a middleware framework of Node.js

But since connect is one of the dependencies of Express, we need not install it separately. If we have installed Express, then we already have connect.

Middeware in Express: Node.js
app.js

1
2
3
4
5
6
7
8
var express = require('express');
var app = express();
 app.use(express.bodyParser());
 app.use(express.methodOverride());
 app.use(express.cookieParser());
 app.use(express.session({secret: "some secret key"}));
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));

express.bodyParser extensible request body parser
express.methodOverride faux HTTP method support
express.cookieParser cookie parser
express.session session management support with bundled MemoryStore
express.static streaming static file server supporting Range and more
express.directory directory listing middleware

Middleware In Express: Node.js



YouTube Link: https://www.youtube.com/watch?v=c4ScybD2690 [Watch the Video In Full Screen.]



For list of all supported middleware, visit senchalabs
Also check the list of all the 3rd-party middleware supported by Connect.

Note: Ordering of these middleware is very important.
For Example:
1. You can only override method after you’ve parsed the body, so methodOverride() must come only after bodyParser()
2. Similarly, session middleware depends on cookieParser(), so session middleware must come only after cookieParser()

As your application becomes popular you’ll need middlewares to handle csrf( Cross-site request forgery ), DDos attacks etc. Also it’s very important to validate the user requests before you allow the user request to fetch the data from your database. Learn to use middleware properly, and I’m sure, it’ll be a life-saver for your application.

Leave a Reply

Your email address will not be published. Required fields are marked *