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..’);

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.





Join Hacker Noon

Create your free account to unlock your custom reading experience.