简体   繁体   中英

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();
});

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

PS 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

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

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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM