Created
November 26, 2018 10:47
-
-
Save ganeshkbhat/d46709118fd6c8cf3dd32707a4acca09 to your computer and use it in GitHub Desktop.
expressjs-before-after-middleware-implement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
const beforeAfterInjection = function(req, res, next) { | |
res.response = function (obj) { | |
req.res = obj; | |
} | |
next(); | |
} | |
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).response({"response":"fine"}); | |
} | |
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(); | |
} | |
const finalResponseHandler = function(req, res, next) { | |
console.log('Final immutable response handler triggered'); | |
res.send(req.res); | |
}; | |
app.get('/implement', beforeAfterInjection, beforeMiddleware, handler, afterMiddleware, finalResponseHandler); | |
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