Node.js Express-rate-limit是什么

Node.js Express-rate-limit是什么

Node.js是一个开源的、跨平台的运行环境,建立在Chrome的V8 JavaScript引擎上,用于在浏览器之外执行JavaScript代码。你需要记住,Node.js不是一个框架,也不是一种编程语言。它提供了一个基于事件驱动、非阻塞(异步)I/O和跨平台的运行环境,用于使用JavaScript构建高度可伸缩的服务器端应用程序。

在这篇文章中,我们将学习关于Express-Rate Limit。

Express Rate Limit: 速率限制防止同一个IP地址发出过多的请求,这有助于我们防止暴力攻击。

所需依赖:

npm install express-rate-limit
JavaScript

项目设置: 运行以下一组命令来创建文件夹和初始化项目。

mkdir test-project
cd test-project
npm init -y
JavaScript

项目结构:

Node.js Express-rate-limit是什么

示例: 在App.js文件中编写以下代码。

// Express is node framework that helps
// in setting up the server and routing.
const express = require("express");
 
// The express-rate-limit is for
// limiting the incoming request.
const rateLimit = require("express-rate-limit");
 
// App variable store the express module.
const app = express();
 
// Creating a limiter by calling rateLimit function with options:
// max contains the maximum number of request and windowMs
// contains the time in millisecond so only max amount of
// request can be made in windowMS time.
const limiter = rateLimit({
    max: 200,
    windowMs: 60 * 60 * 1000,
    message: "Too many request from this IP"
});
 
// Add the limiter function to the express middleware
// so that every request coming from user passes
// through this middleware.
app.use(limiter);
 
// GET route to handle the request coming from user
app.get("/", (req, res) => {
    res.status(200).json({
        status: "success",
        message: "Hello from the GeeksforGeeks express server"
    });
});
 
// Server Setup
const port = 8000;
app.listen(port, () => {
    console.log(`app is running on port ${port}`);
});
JavaScript

运行该应用程序的步骤: 在终端中运行以下命令:

node app.js
JavaScript

输出: 我们将在终端屏幕上看到以下输出。

app is running on http://localhost:8000/
JavaScript
  • 当请求没有超过速率限制器的最大限制时的输出:

Node.js Express-rate-limit是什么

  • 当一个请求超过速率限制器的最大限制时的输出:

Node.js Express-rate-limit是什么

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册