การจำกัดอัตรามีความสำคัญในแต่ละวันในการป้องกันเว็บไซต์จากการโจมตี DOS และ DDOS การจำกัดอัตราจะป้องกันระบบจากคำขอปลอมหรือการโจมตีแบบเดรัจฉานอื่นๆ การจำกัดอัตราจะจำกัดจำนวนครั้งที่ IP สามารถส่งคำขอได้ Expressrate-limit คือแพ็คเกจ npm เพื่อจำกัดจำนวนคำขอจากผู้ใช้
การติดตั้งโมดูลจำกัดอัตรา
เรียกใช้คำสั่งด้านล่างเพื่อติดตั้งโมดูลจำกัดอัตราด่วนในแอปพลิเคชันของคุณ
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\node>> node rateLimit.js
หลังจากรันแอปพลิเคชันโหนดแล้ว ให้ไปที่เบราว์เซอร์ของคุณและกด localhost:8000
คุณจะเห็นหน้าที่คล้ายกันดังแสดงด้านล่าง

ลองกดหรือรีเฟรช URL เดิมมากกว่า 5 ครั้งแล้วคุณจะได้รับข้อผิดพลาดด้านล่าง
