我正在使用express-rate-limit@2.11.0模块,它工作正常,但它会全局阻止API,而不是因为它受到点击而阻止特定的API。
我的代码:
const limiter = new RateLimit({
windowMs: 15*60*1000,
max: 100,
delayMs: 0,
message: '==> You have made too many attempts in a short period of time, please try later',
handler: (req, res) => {
res.format({
json: () => {
res.status(429).json({
message: 'You have made too many attempts in a short period of time, please try later'
});
}
});
},
onLimitReached: (req, res, options) => {
logger.error(options.message, resolveLogger({
reqURL: req.url,
statusCode: options.statusCode
}));
}
});
有人可以建议我如何将其限制为仅针对特定 IP
最佳答案
正如评论中提到的,最好限制反向代理、负载均衡器或 Node.js 应用程序的任何其他入口点的速率
如果这不适合您的应用,我建议 rate-limiter-flexible
const { RateLimiterMemory } = require('rate-limiter-flexible');
const opts = {
points: 100, // 100 points
duration: 15*60, // Per 15 minutes
};
const rateLimiter = new RateLimiterMemory(opts);
const rateLimiterMiddleware = (req, res, next) => {
const isIpLimited = isIpLimited(req.ip);
if (isIpLimited) {
// Consume 1 point for each request
rateLimiter.consume(req.ip)
.then(() => {
// There was enough remaining points
next();
})
.catch((rejRes) => {
// All points consumed
const secs = Math.round(rejRes.msBeforeNext / 1000) || 1;
res.set('Retry-After', String(secs));
res.status(429).send('Too Many Requests');
});
} else {
next();
}
};
app.use(rateLimiterMiddleware);
注意:内存限制器在当前进程内存中工作。还有 Cluster、Redis 和 Mongo 限制器,它们共享状态。
关于javascript - 对特定 IP 而非全局应用速率限制登录 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49569437/