Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

4/07/2013

Understanding express.js middleware

Huh;

I struggled real hard to understand these concepts, which can be confusing, due to node async nature.

Let's start with wiki definition:
In its most general sense, middleware iscomputer software that provides services tosoftware applications beyond those available from the operating system.
Translated to express, middleware is a layer that do all the things beside basic those that node http module offfers.
Express uses connect functionality for that purpost.  In the beginning express and connect were separated ( connect was dependency ), but lately express includes connect by default.
So here are some important points to understand, when dealing with middleware and routing in general in expressjs :
  • Node.js itself offers an http module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.
  • Connect also offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.
  • Express does to Connect what Connect does to the http module: It offers acreateServer method that extends Connect's Server prototype. So all of the functionality of Connect is there, plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.
And final tip - it is very important  to include middleware functionality in the right order in your config. file. Here's a link to help http://www.senchalabs.org/connect/

Happy Coding.


No comments:

Post a Comment