首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何覆盖Node.js模块中的函数?

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

Stack Overflow用户
提问于 2018-08-02 11:55:52
回答 1查看 194关注 0票数 1

我使用以下模块:

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

文件上说:

BruteExpress提供了一些内置回调,用于处理一些常见的用例。

代码语言:javascript
复制
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

定义如下:

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

发布于 2018-08-02 12:54:34

这有点棘手,但您可以重写该方法并保留对旧方法的引用,这样它也可以运行:

代码语言:javascript
复制
 { // 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!" });
  };
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51653033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档