Intro to Express
#HarvestJS
Special Thanks to:
Express Request Handling
- Executed in order
- Callbacks can do 1 of 2 things
- Handle the response
- Pass control on
This is the basis for middleware
Middleware
-
Just functions that handle requests
- Handlers are executed in order
- Handlers can be "stacked"
Route Callback
function(req, res) { //code }
Middleware Callback
function(req, res, next) { //code }
Control is passed along using next();
Route Callback
app.get('/route', function(req, res) {
//code
});
Middleware Callback
app.use(function(req, res, next) {
//code
});Every request goes through the middleware
Examples
-
Authentication
- Authorization
- Static files
-
Body parsing (forms)
- Cookie parsing
Authentication Example
app.use(function(req, res, next) {
if ( ! loggedIn ) {
res.end('You are not authorized');
} else {
next();
}
});
- Show message if not logged in
- Send request on if they are
Middleware
Can also modify the request
app.use(function(req, res, next) {
req.user.name = 'John Lithgow';
req.user.career = 'actor';
req.user.age = '67';
next();
});
-
Will append user to the request object
- req.user will be available in subsequent handlers
Order Matters
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
res.end(404, 'Not found');
});
app.get('/', function(req, res) {
res.send('Hello World');
});
- app.router is used for route handling
- Routes are injected before the 404 Middleware
Express Middleware
By Joe Fleming
Express Middleware
- 2,376