Skip to content

Instantly share code, notes, and snippets.

@Sysetup
Created October 9, 2017 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sysetup/fe4682ebc96fff98b25f5105d5ad7fdb to your computer and use it in GitHub Desktop.
Save Sysetup/fe4682ebc96fff98b25f5105d5ad7fdb to your computer and use it in GitHub Desktop.
Middleware for Express.js
var express = require('express');
var app = express();
var server = app.listen(3000);
function logger(req,res,next){
console.log(new Date(), req.method, req.url);
next();
}
function hello(req,res,next){
res.write('Hello \n');
next();
}
function bye(req,res,next){
res.write('Bye \n');
res.end();
}
app.use(logger);
app.get('/hello',hello,bye);
//-----
$ curl http://localhost:3000/hello
Hello
Bye
$
And the server will log our requests as well:
Mon Mar 23 2015 11:23:59 GMT-0700 (PDT) 'GET' '/hello'
//////////
var app = express();
var apiRouter = express.Router();
apiRouter.use(logger);
app.use('/api',apiRouter);
app.use(hello,bye);
//-----
our server logs the API request:
Mon Mar 23 2015 14:48:59 GMT-0700 (PDT) 'GET' '/hello'
//https://stormpath.com/blog/how-to-write-middleware-for-express-apps
//https://github.com/node-inspector/node-inspector
//////////
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user : req.user // get the user out of session and pass to template
});
});
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
//////////
app.use(getHost,session({
secret: 'nnn',
resave: false,
saveUninitialized: false,
name: 'nnn',
cookie: {
httpOnly: true,
domain: host,
path: '/'
}
}));
function getHost(req, res, next) {
host = req.get('host');
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment