我可以使用 express-rate-limit 为相同的路由设置多个速率限制吗?

Can I set multiple rate limits for the same routes with express-rate-limit?

我可以为我的快速服务器设置全局 rateLimit 并为某些路由设置更严格的 rateLimit 吗?

例如:

const globalLimit = rateLimit({
  windowMs: 60 * 60 * 1000,        // 1 HOUR
  max: 500                         // MAX 500 REQUESTS
});

const apiLimit = rateLimit({
  windowMs: 60 * 60 * 1000,        // 1 HOUR
  max: 100                         // MAX 100 REQUESTS
});

const someRouteLimit = rateLimit({
  windowMs: 60 * 60 * 1000,        // 1 HOUR
  max: 10                          // MAX 10 REQUESTS
});


app.use("/", globalLimit);         // ALL ROUTES WILL BE LIMITED BY THE globalLimit
app.use("/api", apiLimit);         // API ROUTES WILL BE LIMITED BY THE apiLimit

app.get("/some-route", someRouteLimit, routeHandler);  // THIS ROUTE WILL BE LIMITED BY THE someRouteLimit

它会按照我想要的方式工作吗?这是 express-rate-limit 包的正常使用还是反模式?

express-rate-limit 是一个非常流行的包。所以我不认为这是一个反模式。

可以链接中间件。

例如,您想将 someRouteLimitapiLimit 都强加到 /some-route

app.get("/some-route",apiLimit,someRouteLimit,routeHandler)

中间件是按顺序执行的,因此您想将限制性更强的放在宽松的之后。

Express 中间件层次结构:

  1. 应用层中间件
  2. 路由器级中间件

app.use("/", globalLimit) 是一个应用程序级中间件,因此它将在所有其他中间件之前首先执行,但 before/after 其他应用程序级中间件取决于它们被调用的顺序。

您还可以使用路由器对路由进行分组,并在特定路由器上应用速率限制中间件。

在你的app.jsindex.js中:

// Depedencies
const express = require('express')
const rateLimit = require('express-rate-limit')

// Initialize the app
const app = express()

const globalLimit = rateLimit({
  windowMs: 60 * 60 * 1000,        // 1 HOUR
  max: 500                         // MAX 500 REQUESTS
});

const apiLimit = rateLimit({
  windowMs: 60 * 60 * 1000,        // 1 HOUR
  max: 100                         // MAX 100 REQUESTS
});


// Load Routes
const routeOne = require('./routes/routeOne');
const routeTwo = require('./routes/routeTwo');

// Use routes
app.use('/', routeOne,apiLimit); // Impose apiLimit on this router
app.use('/', routeTwo);          // No router-level middleware is applied

app.listen(portNumber)

在routeOne中:(同时受到globalLimitapiLimit的限制)

const express = require('express');
const router = express.Router();
const rateLimit = require('express-rate-limit')

const someRouteLimit = rateLimit({
  windowMs: 60 * 60 * 1000,        // 1 HOUR
  max: 10                          // MAX 10 REQUESTS
});


// Some Route (further restricted by someRouteLimit)
router.post('/some-route',someRouteLimit, routeHandler);

module.exports = router;

在 RouteTwo 中:(受 globalLimit 但不受 apiLimit 限制)

const express = require('express');
const router = express.Router();
const rateLimit = require('express-rate-limit')

const someRouteLimit2 = rateLimit({
  windowMs: 60 * 60 * 1000,        // 1 HOUR
  max: 10                          // MAX 10 REQUESTS
});


// Some Route (further restricted by someRouteLimit2)
router.post('/some-route2',someRouteLimit, routeHandler);

module.exports = router;

如果你想以更自定义的方式实现你的中间件,this post.

中有一些使用正则表达式和自定义辅助函数的更有创意的方法