Mô tả
Giới hạn tỷ lệ (Rate-limiting) ngày càng quan trọng để ngăn chặn website khỏi tấn công DOS & DDOS. Rate-limiting bảo vệ hệ thống khỏi các yêu cầu giả mạo hoặc các cuộc tấn công brute force. Rate limiting giới hạn số lần một IP có thể tạo yêu cầu. express-rate-limit là gói npm để giới hạn số yêu cầu từ người dùng.
Cài đặt module rate-limit
Chạy lệnh dưới để cài đặt module express rate-limiting trong ứng dụng của bạn.
npm install --save express-rate-limit
Ví dụ
Tạo file tên rateLimit.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:
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}`); });Đầu ra
C:\home\node>> node rateLimit.js
Sau khi chạy ứng dụng node, truy cập trình duyệt tại localhost:8000
Bạn sẽ thấy trang tương tự như hình dưới.

Thử truy cập hoặc refresh cùng URL hơn 5 lần và bạn sẽ nhận được lỗi dưới.
