简体   繁体   中英

After modifying express.js res.send function it won't emit any data

Basically what I'm trying to do is unify every response of my application just so they look like this

{
  success: true,
  error: "Error description",
  errorCode: "SomeError",
  data: {
    ...
  }
}

Copying and pasting this structure everywhere as well as wrapper function looks quite ugly to me, so I've tried to modify send function so that it accepts 4 params instead of only 1 and then makes given structure.

I've found various examples on how to modify send function and came up with this middleware

app.use(function (req, res, next) {
  const oldSend = res.send;

  res.send = function (data = {}, success = true, error = '', errorCode = '') {
    let response = {
      data,
      success,
      error,
      errorCode
    };

    oldSend.apply(res, response);
  };

  next();
});

so the res.send call looks like this

res.json(req.session.key != null, true, null, null);

Which works fine except it doesn't return any response to the client. Could you help me solve this? Is it possible to achieve expected behaviour?

You are using function.apply which expects a this and then an array of the function arguments (see MDN for function.prototype.apply ). What you need to use instead is function.call (again see MDN for function.prototype.call ).

However, a word of caution to be careful of overwriting a low level part of express (or any library) - you don't know what else might be calling this so you may get some unexpected results. You might like to check (for example) that the supplied parameter is of a type which you expect (eg an object) and pass anything unexpected (eg a Buffer ) straight through to the original send.

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