【问题标题】:How can I override a function in a Node.js module?如何覆盖 Node.js 模块中的函数?
【发布时间】:2018-08-02 11:55:52
【问题描述】:

我正在使用以下模块:

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。

【问题讨论】:

  • 你覆盖它就像它被定义一样。
  • 但是函数 'setRetryAfter' 是 index.js 内部的,并且无法从我要覆盖的地方访问?
  • 显然ExpressBrute.FailTooManyRequests 只是failCallback 选项的默认值。将选项设置为其他选项,您会没事的。

标签: javascript node.js


【解决方案1】:

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

 { // 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!" });
  };
}

【讨论】:

  • 我认为OP实际上想要覆盖ExpressBrute.defaults.failCallback
  • @bergi 不知道库,但听起来好像你是对的
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 2012-03-06
  • 1970-01-01
相关资源
最近更新 更多