simd
simd

Reputation: 2019

Override Node.js Express response method

I want to slightly change default expressjs behaviour of res.json(obj) method. I am trying to override it in my own middleware, the thing is I need to call its original inside.

But now it just calls itself causing a stack overflow.

app.use(function(req, res, next) {
    res.json = function(obj) {
        function delete_null_properties(obj) {
            // ...
        }
        delete_null_properties(obj);

        res.json(obj);
    };
    next();
});

Upvotes: 1

Views: 7942

Answers (3)

STEVE  K.
STEVE K.

Reputation: 909

You can do like below, after const app = express(); dont use this.json and dont use this.send inside the function otherwise you will get a maximum call size error :

app.response.json = function(body: any) {
    this.contentType('json').end(JSON.stringify(
      {
          code: ApiCode.OPERATION_SUCCES,
          message: CommonMessages.OperationSuccess.message,
          data: body,
          description: CommonMessages.OperationSuccess.description
        }
    ));
    return this; 
}

Upvotes: 0

OlegDovger
OlegDovger

Reputation: 122

It also might be useful

https://github.com/muratcorlu/connect-api-mocker/pull/30

Mounting twice will apply only last one.

const express = require('../../node_modules/express');

const app = express();

// default response
app.use('/', (req, res, next) => {
  next();

  try {
    res.send({
      profile: {
        first_name: 'Aaron',
        last_name: 'Pol'
      }
    });
  } catch (e) {
    //
  }
});

// definite state, where default response can be changed
app.use('/', (req, res) => {
  res.send({
    profile: {
      first_name: 'John',
      last_name: 'Pol'
    }
  });
});

app.listen(9090);

Upvotes: -1

Jaromanda X
Jaromanda X

Reputation: 1

I don't know the inner workings of express very well, but it seems something like this should work

app.use(function(req, res, next) {
    var json = res.json;
    res.json = function(obj) {
        function delete_null_properties(obj) {
            // ...
        }
        delete_null_properties(obj);

        json.call(this, obj);
    };
    next();
});

edit: changed json(obj) to json.call(this, obj) as per comment by user3537411 and this previous answer to a similar question

P.S. I started the answer with I don't know the inner workings of express very well to avoid the sort of comments that just put crap on an answer without really going into WHY an answer is bad ... instead I get the sort of comment that's equally pointless. You can't win with SO trolls

Upvotes: 18

Related Questions