簡體   English   中英

在 Node js 中使用 express-rate-limit 框架的 API 的剩余限制

[英]Remaining limits of an API using express-rate-limit framework in Node js

我正在創建一個 api,我想在其中限制對 api 的調用次數。 我正在使用 Express-rate-limit 框架來創建限制。 但我也想顯示用戶的請求數。

PS 我是 Node.js 的新手

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

const rateLimiter = rateLimit({
  windowMs: 1 * 60 * 1000, 
  max: 5,
  statusCode : 403,
  message: 'You have exceeded the 5 requests in 1 min limit!',
  headers: true,
});


router.get("/call_api", checkauth,rateLimiter, async function(req,res,next)  {


    await fetch("http://localhost:8000/get_number", {
        method : "GET",
        // headers: {'Content-Type': 'application/json'},
    })
    .then((response) => response.json()).then((response1) => {
        res.status(200).json({
            number : response1.number
        });
    })

    // res.status(200).json({
    //     message : "Generating a random number"
    // })
  });

router.get("/remaining_limit",checkauth,rateLimiter, (req,res) => {
      res.status(500).json({
          remaining_limits : "You have _ remaining limits" //the number of remaining limits
      });
  })

文檔引用了一個請求 API

一個req.rateLimit屬性被添加到所有請求中,包括limitcurrentremaining請求數,如果商店提供它,還添加一個resetTime Date object。 這些可以在您的應用程序代碼中使用,以采取其他操作或通知用戶他們的狀態。

您的/remaining_limit端點可能是這樣的:

router.get("/remaining_limit",checkauth,rateLimiter, (req,res) => {
  const remaining = req.rateLimit.remaining;
  res.status(200).json({ 
  // Note that we return 200 OK because the endpoint is working as it should - returning a value
  remaining_limits : `You have ${remaining} remaining limits` // using a template literal
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM