如何覆盖Node.js模块中的函数?

时间:2018-08-02 11:55:53

标签: javascript node.js

我正在使用以下模块:

https://github.com/AdamPflug/express-brute

文档说:

  

BruteExpress附带了一些内置的回调,可以处理一些常见的用例。

ExpressBrute.FailTooManyRequests Terminates the request and responses with a 429 (Too Many Requests) error that has a Retry-After header and a JSON error message.

源代码:

https://github.com/AdamPflug/express-brute/blob/36ddf21d0989f337a6b95cd8c945a66e32745597/index.js

定义以下内容:

ExpressBrute.FailTooManyRequests = function (req, res, next, nextValidRequestDate) {
    setRetryAfter(res, nextValidRequestDate);
    res.status(429);
    res.send({error: {text: "Too many requests in this time frame.", nextValidRequestDate: nextValidRequestDate}});
};

如何覆盖该函数以使其执行我想做的事情?特别是,我不想使用res.send发送JSON消息,而是希望使用res.render显示一些HTML。

1 个答案:

答案 0 :(得分:0)

这有点棘手,但是可以覆盖该方法并保留对旧方法的引用,以便它也可以运行:

 { // scope to keep old private
   const old = ExpressBrute.FailTooManyRequests;
   ExpressBrute.FailTooManyRequests = function (req, res, next, nextValidRequestDate) {
      // Call the old one but replace res with a fake response
      old(req, { send() {}, status() {} }, next, nextValidRequestData);
      res.json({ what: "ever!" });
  };
}
相关问题