Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ganeshkbhat/a19ed61c45ae49ba85aa2953ade91995 to your computer and use it in GitHub Desktop.
Save ganeshkbhat/a19ed61c45ae49ba85aa2953ade91995 to your computer and use it in GitHub Desktop.
ExpressJS before after middleware implementation after sending response
const express = require('express');
const app = express();
const beforeMiddleware = function(req, res, next) {
console.log('Before middleware triggered');
next();
}
const responseHandler = function(req, res, next) {
console.log('Response Action implementation triggered with response instead of send');
res.status(200).send({"response":"fine-as-normal"});
}
const handler = function(req, res, next) {
console.log('Response Action implementation is not passed to express. Rather handler is triggered');
responseHandler(req, res, next);
next();
};
const afterMiddleware = function(req, res, next) {
console.log('After middleware triggered');
next(); /* Can be removed safely */
}
app.get('/implement', beforeMiddleware, handler, afterMiddleware);
app.listen(9001, '127.0.0.1', function() {
console.log('Server started at port ' + 'localhost' + ':' + 9001);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment