Map functions to a (set of) routes
http://expressjs.com/en/guide/using-middleware.html
request
response
Arguments:
request
response
next
function middleware(req, res, next){
//do some stuff
next(); //go to next matching middleware/route
}
function middleware(req, res, next){
doSomethingAsync(function done(err, results){
if(err){ return next(err); }
req.extraStuff = results;
next();
})
}
app.use(middleware);
app.use(path, middleware);
app.get(path, middlewareOne);
app.post(path, middlewareTwo);
app.delete(middlewareThree);
app.get('/', function(req, res, next){
/* run first */
next();
});
app.get('/', function(req, res, next){
/* run second */
res.send('done!');
});
app.get('/', function(req, res, next){
/* never runs */
next();
});
app.use(function(req, res, next){
req.foo = 'something';
});
Generated placeholder images
//GET /placeholder/png?size=200x300
//GET /placeholder/jpg?size=10x20
//GET /placeholder/jpg?x=100&y=200
//GET /placeholder/gif?x=50&y=20
app.get('/placeholder/*', function(req, res, next){
if(req.query.size){
req.dimensions = req.query.size.split('x');
}else if(req.query.x && req.query.y){
req.dimensions = [req.query.x, req.query.y];
}else{
req.dimensions = [200, 200];
}
next();
});
app.get('/placeholder/gif',function(req, res){
var img = generateImage(req.dimensions);
/*...*/
body-parser
cookie-parser
express-session
start/restaurants-router-4.js
POST /restaurants
accepts json inputHints:
body-parser
(npm install!)/users/users
)nodemon start/restaurants-server-4.js
Extra Credit:
id
& add id
automatically//express-app/misc/res.uptime-header.js (exerpt)
var startTime = Date.now();
app.use(function uptimeMiddleware(req, res, next){
res.set('X-app-Uptime', Date.now() - startTime);
next();
});
compression
response-time
express-partial-response
Create middleware/logger.js
to log all requests thus:
Sun Mar 06 2016 18:26:39 GMT-0800 (PST): GET /
Sun Mar 06 2016 18:26:41 GMT-0800 (PST): GET /users
Sun Mar 06 2016 18:27:18 GMT-0800 (PST): POST /users
Hints:
next()
Extra Credit:
morgan
Respond (or error) immediately for certain requests
//reject unlucky requests
app.use(function(req, res, next){
if(Math.random() > .5){
console.error('UNLUCKY USER!!!');
res.status(403).send('Not Authorized (Unlucky User)');
}
else{
next();
}
});
app.get('/', function(req, res){
/*...*/
passport
express.static
serve-index
express-app/start/static-server.js
Use the express.static
middleware to serve express-app/assets/
Hints:
index.html
by defaultUp Next: Error Handling
Arguments:
error
request
response
next
function errorMiddleware(err, req, res, next){
res
.status(err.code)
.send(err.message);
}
app.use('/', rootHandler);
app.use('/user', userRouter);
//...
app.use(errorHandlerMiddleware);
app.get('/user/:id', function(req, res, next){
db.Users.get({id: req.params.id}, function(err, user){
if(err){
next(err);
}else{
res.json(user);
}
});
});
app.use(function(err, req, res, next){
console.error(err);
res.status(500).send('Error');
});
app.use(someLoginMiddleware);
app.use('/account/*', function gateAdminArea(req, res, next){
if(!req.user){
var e = new Error('Please log in');
var e.code = 403;
next(e);
}
});
app.use('account/edit', /*...*/);
app.use('account/subscriptions', /*...*/);
// ...
app.use(function(err, req, res, next){
/* handle error */
});
app.get('/post/:id', function gateAdminArea(req, res, next){
db.Posts.get({id: req.params.id}, function(err, post){
if(err){
//there was an internal/db error
err.code = 500;
next(err);
}else if( isEmpty(post) ){
next(makeError('Post Not Found!', 404));
}
else res.json(post);
}
});
app.use(function handle404(err, req, res, next){
if(err.code !== 404) return next(err);
logger.info('NOT FOUND: ' + req.originalUrl');
next(err);
});
app.use(function handle500(err, req, res, next){
if(err.code < 500 || err.code > 599) return next(err);
logger.urgent(err.message);
emailAdmin(new Date(), err.toString());
next(err);
});
app.use(function errorPage(err, req, res, next){
res.render('error_page', err);
});
app.use(404Handler);
app.use(OtherErrorHandler);
app.use(500Handler);
app.use(function catchallErrorHandler(err, req, res, next){
res.status(500).send('We do not know what happened... sorry!');
});
app.get('/', /*...*/);
app.get('/admin', /*...*/);
app.get('/post/:id', /*...*/);
app.post('/post/:id', /*...*/);
/* ... */
app.use(function catchallRoute(req, res, next){
next(makeError('We couldn\'t find it!', 404));
});
Up Next: Templates