Before you go, check out these stories!

0
Hackernoon logo[ Expressjs ] Cracking nuts, override res.send by@peterchang_82818

[ Expressjs ] Cracking nuts, override res.send

Express.js is the shell of nuts, which has well architect and basic protected functionality, the logic inside is the fresh of nuts, which gives the taste and make nuts different.

I am a big fan of Express.js and has been using it for many projects, my favourite part is middleware pattern and routers design which relieve so much pain in building HTTP servers.

My boss threw me a feature yesterday :

“Peter, we need a thingy to monitor the user behaviour in the APP.” 
“I think GA is already added in the APP?” 
“We need more detail from the user, but they are not stored in GA (like money flow), and GA has a disadvantage, it is not easy to do search.” 
“I see, a module to store every detail of each request (GET, POST, PUT),
a log module, is needed to record and monitor, when Error or Exception is happened at least we have a lead from the record to find the reason.”

The best solution will be manipulating the res.send( ) function, just few line of program:

var express = require(‘express’) 
var app = express()

// Overwrite res.send
app.use(function(req, res, next) {
var temp = res.send
res.send = function() {
console.log(‘do something..’);
temp.apply(this,
arguments);
}
next();

})
app.get(‘/’, function (req, res) {
res.send(‘Hello World!’)
})

#Thanks to Vladimir de Turckheim, advised to use temp.apply(this, arguments) for better flexibility code usage

You also like Cracking nuts series:

[Javascript] override Object.constructor( )
[Expressjs] put the IP to BlackList

Like this story? It is helpful to others? It helps me know if you’d like to see write more about his topic and helps people see the story, when tap the heart below.

Reference:

http://stackoverflow.com/questions/27885425/express-middleware-before-response-is-carried-out-to-client

https://github.com/wahengchang/javascript-must-know/blob/master/middleware_overwrite_res.send/app.js

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!