如何在node.js中使用'limiter'

时间:2018-05-22 05:39:08

标签: node.js express npm spam-prevention throttling

我正在尝试在我的应用中实施一些反垃圾邮件机制。我遇到了the limiter package

阅读他们的例子后,我很困惑:

var RateLimiter = require('limiter').RateLimiter;
var limiter = new RateLimiter(150, 'hour', true);  // fire CB immediately

// Immediately send 429 header to client when rate limiting is in effect
limiter.removeTokens(1, function(err, remainingRequests) {
  if (remainingRequests < 1) {
    response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'});
    response.end('429 Too Many Requests - your IP is being rate limited');
  } else {
    callMyMessageSendingFunction(...);
  }
});

“响应”定义在哪里?我们不需要使用app.use()将限制器挂钩到路径吗?限制器如何知道传入的IP呢?

1 个答案:

答案 0 :(得分:2)

我几天前尝试过这个套餐。该包用于记录一段时间内的请求计数。请求来自何处并不重要。所以这个包不关心传入的IP地址是什么。

确实,我们需要在应用程序中间件中添加代码以限制整个应用程序,或者为指定路径添加路径中间件。然后,您可以获得响应对象。以下是一个简单的用法。

var express = require('express')
var app = express()

app.use(function (req, response, next) {
  limiter.removeTokens(1, function(err, remainingRequests) {
      if (remainingRequests < 1) {
        response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'});
        response.end('429 Too Many Requests - your IP is being rate limited');
      } else {
        next();
      }
    });
})

如果要跟踪指定的IP地址。我建议express-rate-limitexpress-limiter