gpt4 book ai didi

javascript - 如何重写 Node.js 模块中的函数?

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:29 31 4
gpt4 key购买 nike

我正在使用以下模块:

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

文档说:

There are some built-in callbacks that come with BruteExpress that handle some common use cases.

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。

最佳答案

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

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

关于javascript - 如何重写 Node.js 模块中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51653033/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com