![](/img/trans.png)
[英]Remaining limits of an API using express-rate-limit framework in Node js
[英]How to increase the blocking time period after being rate limited using express-rate-limit in Node js?
express-rate-limit
庫將在超過每個時間單位的一定數量的請求后阻止來自客戶端的連接(假設由 IP 標識)。 它還會在相當於時間單位的時間內阻塞連接。
因此,如果設置為每分鍾 120 個請求后阻止連接; 它還會阻塞 IP 一分鍾。 我怎樣才能延長阻塞時間?
這是我當前的示例:
...
var express = require('express');
var app = express();
const RateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
limiter = new RateLimit({
store: new RedisStore({
expiry: 60
}),
max: 120
});
app.use(limiter);
...
這里我也是用rate-limit-redis
,它的expiry
參數覆蓋了express-rate-limit
的windowMs
參數。
通過使用onLimitReached
回調,您可以記錄 IP 再次解鎖的時間。 然后,您可以編寫另一個中間件來檢查何時達到解鎖日期。
在下面的示例中, bannedIPs
記錄了 IP 再次被解鎖的時間, banner
是使用該時間根據當前日期對 IP 進行解鎖的中間件。
...
var express = require('express');
var app = express();
const RateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
// Keep the IPs that are banned
const bannedIPs = {};
limiter = new RateLimit({
store: new RedisStore({
expiry: 60
}),
onLimitReached: function(req, res, options) {
// The IP will be unblocked again in an hour (60*60*1000)
bannedIPs[req.ip] = +new Date() + 60*60*1000;
},
max: 120
});
banner = function(req, res, next) {
// If the current Date is still before than the unblocking date,
// send a 429 message indicating too many requests
if (bannedIPs[req.ip] >= +new Date()) {
res.status(429).send("Sorry, too many requests: " + new Date(bannedIPs[req.ip]));
} else {
next();
}
}
app.use(banner);
app.use(limiter);
...
有很大的改進空間,例如一旦不再被阻止就刪除IP,並且可能將密鑰存儲在Redis中,以便在重新啟動服務器后保持不變。 但是,這將為您提供一個起點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.