Connect is a middleware framework for Nodejs and is used in several projects like Express. Today I’ll show you a simple example of how to use some of the Connect bundled middleware in an Express application.
Assuming you have Nodejs installed and are ready to go, make sure to use npm to install the latest Express. I’ll install mine locally to the folder I’m currently working in like this:
$ npm install express
Lets use the Connect logger and responseTime middleware. The logger gives a configurable output and the responseTime will tell you how long a response took by placing a value in the headers (X-Response-Time).
Create a new file called app.js and add the following code:
var express = require('express');
var app = express.createServer(
express.logger(),
express.responseTime()
);
app.get('/', function(request, response) {
response.send('Hello World');
});
console.log('Starting server...')
app.listen(8080);
Update Sept 14, 2012: With Express 3 keep in mind that createServer has been deprecated. You can modify the above code like below to get rid of the deprecation warning:
app = express(); app.use(express.bodyParser())
You can see how easy it is to add Connect middleware. Using Express you simply add the middleware you want, in this case I added it in via createServer.
Now go to the URL (you might want to use a browser add-on to see the headers more easily, for Chrome try the XHR Poster). In the header you should see something similar to this:
X-Response-Time 0ms
Obviously our server is so fast at this point since it only serves up the text “Hello World” that it took essentially no time to process and response. However if you were actually doing some something more you will see the value go up. Just as an example you could temporarily block the server with a timer if you wanted to see the value change.
In the output you will see the logging:
127.0.0.1 - - [Sun, 15 Jan 2012 23:57:13 GMT] "GET / HTTP/1.1" 200 11 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7"




Pingback: Nodejs: Using Connect’s BasicAuth with Express | Giant Flying Saucer