在 Node.js 中集成 Express-rate-limit
限速日益重要,可以防止网站遭受 DOS 和 DDOS 攻击。限速可防止系统遭受任何类型的虚假请求或其他暴力攻击。限速限制了 IP 可以发出请求的次数。expressrate-limit 是用于限制用户请求次数的 npm 包。
安装 rate-limit 模块
运行以下命令在您的应用程序中安装 Express 限速模块。
npm install --save express-rate-limit
示例
创建一个名为 rateLimit.js 的文件,并复制以下代码段。创建文件后,使用以下命令运行此代码,如下面的示例所示 −
node rateLimit.js
rateLimit.js
// Importing the express dependency
const express = require("express");
// Importing the express-rate-limit dependency
const rateLimit = require("express-rate-limit");
// Storing the express function in variable application
const applicaion = express();
// Calling the ratelimiter function with its options
// max: Contains the maximum number of requests
// windowsMs: Contains the time in milliseconds to receive max requests
// message: message to be shown to the user on rate-limit
const limiter = rateLimit({
max: 5,
windowMs: 60 * 60 * 1000,
message: "Too many request from this IP"
});
// Adding the rate-limit function to the express middleware so
// that each requests passes through this limit before executing
applicaion.use(limiter);
// GET route for handling the user requests
applicaion.get("/", (req, res) => {
res.status(200).json({
status: "SUCCESS",
message: "Welcome to TutorialsPoint !"
});
});
// Server Setup
const port = 8000;
applicaion.listen(port, () => {
console.log(`app is running on port ${port}`);
});输出
C:\home
ode>> node rateLimit.js
运行 node 应用程序后,转到您的浏览器并点击 localhost:8000
您将看到一个类似于下图的页面。

尝试点击或刷新相同的 URL 超过 5 次,您将收到以下错误。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP