Database Reference
In-Depth Information
connect framework with express middleware. These two packages form
the basis of the web applications developed in this chapter.
HTTP Middleware with Connect
The connect framework is often compared to Ruby's rack project. It
builds on the basic HTTP server library to provide chainable pieces of code
called middleware . These pieces of code—the core library contains nearly
two dozen—are used to provide various components of a web server, such as
query string parsing, authentication, or file serving.
Implementing a basic server capable of delivering static files only requires a
few lines of code:
var connect = require('connect')
;
var app = connect()
.use(connect.static('public'))
.use(function(request,response) {
response.writeHead(404,{'content-type':'text/
plain'});
response.end("File Not Found");
})
.listen(3000);
This server first creates a connect application by calling connect() and
then begins chaining together middleware with the use() function. Each
piece of middleware is executed in the order it was added for each request.
Writing custom middleware is also easy because it is simply comprised
of functions. All middleware functions take the form
function ( request , response , next ) where the function may modify
the request and response values before optionally calling the next
function to proceed to the next piece of middleware.
Configuration of the middleware usually takes place by implementing a
function that returns the middleware itself. This allows the middleware to
be configured by taking advantage of the lexical scoping of JavaScript. For
example, to implement a simple version of the static middleware might
look something like this:
Search WWH ::




Custom Search