Node.js - Express
Updated at 2013-07-04 06:04
Express is Node.js web application framework. These notes contain some basic usage examples how to use express.
Basic express server.
var express = require('express');
var app = express();
app.get('/hello', function(request, response){
var body = 'Hello World';
response.setHeader('Content-Type', 'text/plain');
response.setHeader('Content-Length', body.length);
response.end(body);
// or just res.send('Hello World');
});
app.listen(3000);
console.log('Listening on port 3000');
Error handling is done by defining own middleware after other middleware. Not mandatory but an unwritten standard. Middlewares should always pass the error to next middleware by using next(error)
.
// app.use([path], function), where path is where it applies and function
// the middleware. Path defaults to '/'.
// Other middleware.
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
// Error handling.
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
// Generic error logging to console.
function logErrors(error, request, response, next) {
console.error(error.stack);
next(error);
}
//
function clientErrorHandler(error, request, response, next) {
// is the the request AJAX? (XMLHttpRequest)
if (request.xhr) {
response.send(500, { error: 'Something blew up!' });
}
else {
next(error);
}
}
// Error handler that catches everything.
function errorHandler(error, request, response, next) {
response.status(500);
response.render('error', { error: error });
}
Express is built on top of Connect which is built on top of Node. So all underlying functionality and middleware are usable.
Sending a raw file with express.
response.sendFile(__dirname + '/tweets.html');
Redirecting with express.
response.redirect(301, 'http://www.example.com');
Express views.
// Start Express
var express = require('express');
var app = express();
// Set the view directory to /views
// Imagine the re is index.jade in there.
app.set('views', __dirname + '/views');
// Let's use the Jade templating language
app.set('view engine', 'jade');
// app.engine('jade', require('jade').__express);
app.get('/', function(request, response) {
response.render('index', { message: 'I love anime.' });
});