After installing node (download), create a directory on your machine and start your first application.
$ mkdir hello-world
In this directory you will define the application "package", which is no different from any other node package. The json file in the file directory clearly defines a dependency. You can use the npm command to get the latest version of Express, which you like to do, instead of installing a version other than "3.x" to prevent any unknown surprises.
{ "name": "hello-world", "description": "hello world test app", "version": "0.0.1", "private": true, "dependencies": { "express": "3.x"}}Now, you have a package. In this directory, you can use npm(1) to install this dependency, in this case you only need to enter:
$ npm install
Once npm is finished, you will have a Express 3.x you depend on in the /node_modules directory. You can verify this with npm ls, just like the Express tree and its own dependencies shown in the following code snippet.
$ npm [email protected] /private/tmp└─┬ [email protected] ├── [email protected] ├─┬ [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ └── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├─┬ [email protected] │ └── [email protected] └─┬ [email protected] └── [email protected]
Now create the application itself! Create a file called app.js or server.js, no matter which one you like, introduce express, and then use express() to create a new application:
var express = require('express');var app = express();New application instances can start defining routes through app.VERB(), in which case, respond to the "GET/" request via the "Hello World" string. req and res are the exact same node objects provided to you, so you might call res.pipe(), req.on('data', callback) and other things you would do that have nothing to do with Express.
Express enhances these objects to provide you with higher-level interfaces such as res.send(), in addition to adding content length to you:
app.get('/hello.txt', function(req, res){ res.send('Hello World');});Now call the app.listen() method for the connection to bind and listen, accepting the same parameters as the node's net.Server #listen():
var server = app.listen(3000, function() { console.log('Listening on port %d', server.address().port);});Use express(1) to generate the application
The Express team maintains a convenient project generator named express-generator(1). If you install express-generator globally with npm, you can access it from anywhere on your computer:
$ npm install -g express-generator
This tool provides an easy way to get an application framework, but with limited scope, for example, it supports only a few template engines, and Express itself actually supports building any website framework templates for node. You can view it through help:
Usage: express [options]Options: -h, --help output usage information -V, --version output the version number -e, --ejs add ejs engine support (defaults to jade) -H, --hogan add hogan.js engine support -c, --css add stylesheet support (less|stylus|compass) (defaults to plain css) -f, --force force on non-empty directory
If you want to generate an application that is supported in any case you just need to simply execute::
$ express --css stylus myappcreate : myappcreate : myapp/package.jsoncreate : myapp/app.jscreate : myapp/publiccreate : myapp/public/javascriptscreate : myapp/public/imagecreate : myapp/public/stylesheetscreate : myapp/public/stylesheets/style.stylcreate : myapp/routes/index.jscreate : myapp/views/index.jadecreate : myapp/views/layout.jadeinstall dependencies:$ cd myapp && npm installrun the app:$ DEBUG=myapp node app
Like any other node application, you must install the following dependencies:
Then let's get started.
$ npm start
This is all you need to get a simple application up and running. Remember, Express is not bound to any specific directory structure, these are just a guide for you. The selection of application structure can be viewed in the github repository.
Error handling
Error handling middleware definitions are like ordinary middleware, but 4 parameters must be defined, which is the function signature (err, req, res, next):
app.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!');});Although forced error handling middleware is not usually defined at the end, after other app.use(), its call looks like this:
var bodyParser = require('body-parser');var methodOverride = require('method-override');app.use(bodyParser());app.use(methodOverride());app.use(app.router);app.use(function(err, req, res, next){ // logic});The response in these middleware is completely arbitrary. You may want to respond to an HTML error page, a simple message, a JSON string, or any other response you like.
To build an organized and higher-level framework, you can define several of these error handling middleware, just like you would define normal middleware. For example, suppose you want to define an error handler for an XHR request, in addition to these, what you might do is as follows:
var bodyParser = require('body-parser');var methodOverride = require('method-override'); app.use(bodyParser());app.use(methodOverride());app.use(app.router);app.use(logErrors);app.use(clientErrorHandler);app.use(errorHandler);In more general logErrors, you can write requests and error messages to stderr, loggly, or similar services:
function logErrors(err, req, res, next) { console.error(err.stack); next(err);}The definition of clientErrorHandler is shown below, Note that this error will be explicitly passed to the next one.
function clientErrorHandler(err, req, res, next) { if (req.xhr) { res.send(500, { error: 'Something blew up!' }); } else { next(err); }}The following errorHandler "all-round" implementation can be defined as:
function errorHandler(err, req, res, next) { res.status(500); res.render('error', { error: err });}User counting online
This section explains a (small) application in detail and uses Redis to track the number of users online. First create a package. The json file contains two attachments, one for the redis client and the other for the Express itself. Also make sure you have wrapped redis and run through $redis-server.
{ "name": "app", "version": "0.0.1", "dependencies": { "express": "3.x", "redis": "*" }}Next, you need to create an application, and a connection to redis:
var express = require('express');var redis = require('redis');var db = redis.createClient();var app = express();The next middleware tracks online users. Here we will use the sorted set so that we can query online users by redis, which only takes N milliseconds. We use timestamps as the "online standard" for members. Note that here we use the user-agent string instead of the usual user id.
app.use(function(req, res, next){ var ua = req.headers['user-agent']; db.zadd('online', Date.now(), ua, next);});The next middleware is to use zrevrangebyscore at the last minute to get the maximum number of online users, we always get the most recent online users, and his upper limit is the current timestamp minus 60000 milliseconds.
app.use(function(req, res, next){ var min = 60 * 1000; var ago = Date.now() - min; db.zrevrangebyscore('online', '+inf', ago, function(err, users){ if (err) return next(err); req.online = users; next(); });});Finally, we use it through a url and bind it to a port! That's all, accessing this app in a new browser and you'll see an increase in number of people online.
app.get('/', function(req, res){ res.send(req.online.length + ' users online');});app.listen(3000);Reverse proxy for Express
Using Express behind reverse proxy, such as Varnish or Nginx is trivial, however it requires configuration. By enabling the "Trust Proxy" setting app.enable("trust proxy"), Express has some tricks for reverse proxying, X-Forwarded-* header fields may be trustworthy, otherwise they may be easily tricked.
Enabling this setting has some subtle effects. The first is that X-Forwarded-Proto may be set by reverse proxy, telling the app that it is https or just a simple http. This value is reflected by req.protocol.
The second change is that the req.ip and req.ips values will fill the list of X-Forwarded-For addresses.
Debug Express
Express uses the debug module internally to record information about path matching and application patterns. To see this message, simply set the debug environment variable to express:*, and after starting the application, you will see the debug information in the console.
$ DEBUG=express:* node ./bin/www
Running this hello world example will print the following:
express:application booting in development mode +0msexpress:router defined get /hello.txt +0msexpress:router defined get /hello.txt +1ms
In addition, the program generated by expressing executable (generator) also uses a debug module, and the default scope is the my-application debug namespace.
You can enable these debugging statements with the following command
$ DEBUG=my-application node ./bin/www
For more information about debugging, see the Debugging Guide