NodeJS express-rate-limit阻止我的客户端应用程序IP而不是用户IP的请求

yxyvkwin  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(216)

我有以下问题。我在DigitalOcean上部署了两个应用程序API(使用Nodejs和express)和CLIENT(create-react-app)。我想添加一个API调用速率限制器。我试过使用express-rate-limiter,但是如果我理解正确的话,它会阻止使用CLIENT应用IP的请求,所以当它达到允许的最大api调用时,express-rate-limiter阻塞所有请求。

import rateLimit from "express-rate-limit";

const apiCallRateLimiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 1,
  message: "You have reached maximum retries. Please try again later",
  statusCode: 429,
  headers: true,
});

app.use(apiCallRateLimiter);
app.use("/", router);

我试过这个express-rate-limit blocking requests from all users,但是它不起作用。中间件看起来像这样

import rateLimit from "express-rate-limit";
import { mw } from "request-ip";

const apiCallRateLimiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 1,
  message: "You have reached maximum retries. Please try again later",
  statusCode: 429,
  headers: true,
  keyGenerator: (req, res) => req.clientIp
});

app.use(mw());
app.use(apiCallRateLimiter);
app.use("/", router);

如何限制API调用获取用户IP而不是我的CLIENT应用IP?

insrf1ej

insrf1ej1#

我刚刚将keyGenerator中的arrow函数更改为匿名函数,现在它可以工作了

const apiCallRateLimiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 1,
  message: "You have reached maximum retries. Please try again later",
  statusCode: 429,
  headers: true,
  keyGenerator(req) {
    return req.clientIp;
  },
});

相关问题