简体   繁体   English

如何使用 express-rate-limit 设置 X-RateLimit-Reset?

[英]How to set X-RateLimit-Reset with express-rate-limit?

I want to set a custom time that a user must wait if they hit a rate limit.我想设置用户在达到速率限制时必须等待的自定义时间。 I am using express-rate-limit and thought I could do this by setting a custom X-RateLimit-Reset in the handler .我正在使用express-rate-limit认为我可以通过在handler设置自定义X-RateLimit-Reset来做到这一点。 I can set this value, but it does not appear to have any effect.我可以设置这个值,但它似乎没有任何效果。

As an extreme example, I tried to block them for a very long time in the future using the following in my handler:作为一个极端的例子,我试图在我的处理程序中使用以下内容在很长一段时间内阻止它们:

res.setHeader('X-RateLimit-Reset', Date.now() + 100000000000)

Console logging res after this results in something correct:控制台登录res ,这会产生无误后:

 'x-ratelimit-reset': [ 'X-RateLimit-Reset', 1566112162159 ] // <-- far in the future

However, after doing this, a user is still able to call the function that should have been rate limited.但是,执行此操作后,用户仍然可以调用本应进行速率限制的函数。 How can I set a custom reset time for a user?如何为用户设置自定义重置时间?

First of all, as you've not mentioned it, I'm assuming you're using the default MemoryStore that comes with the express-rate-limit.首先,正如您没有提到的,我假设您使用的是 express-rate-limit 附带的默认 MemoryStore。 So to answer your question, you don't have to manually set the x-ratelimit-reset header in the response, the package does it for you.因此,要回答您的问题,您不必在响应中手动设置x-ratelimit-reset标头,该程序包会为您完成。

  • So if you're using the default MemoryStore, the configuration looks like this,所以如果你使用默认的 MemoryStore,配置看起来像这样,
app.use(
    RateLimit({
        windowMs: 10 * 60 * 1000 , // 10 minutes
        max: 100, // limit each IP to 100 requests per windowMs
        message: 'You have exceeded the 100 requests in 10 minutes limit!',
    })
);
  • And, if you're using a store other than the default one, you can add the store config in it,而且,如果您使用的是默认商店以外的商店,则可以在其中添加商店配置,
app.use(
    RateLimit({
        store: new MongoStore({
            uri: 'mongodb://localhost:27017/your-db-name',
            expireTimeMs: 10 * 60 * 1000 // 10 minutes
        }),
        windowMs: 10 * 60 * 1000 , // 10 minutes
        max: 100, // limit each IP to 100 requests per windowMs
        message: 'You have exceeded the 100 requests in 10 minutes limit!',
    })
);

Just to note here, rate-limt-redis store has some problems with x-ratelimit-reset header and doesn't work as expected.在这里需要注意的是, rate-limt-redis存储在x-ratelimit-reset标头方面存在一些问题,并且无法按预期工作。 So, you can go ahead with other options.因此,您可以继续使用其他选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM