【问题标题】:Remaining limits of an API using express-rate-limit framework in Node js在 Node js 中使用 express-rate-limit 框架的 API 的剩余限制
【发布时间】:2021-02-24 22:14:22
【问题描述】:

我正在创建一个 api,我想限制对 api 的调用次数。我正在使用 Express-rate-limit 框架来创建限制。 但我也想显示用户的请求数。

附:我是 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
      });
  })

【问题讨论】:

    标签: node.js rest express rate-limiting


    【解决方案1】:

    文档引用Request API

    req.rateLimit 属性添加到所有请求数量为limitcurrentremaining 的请求中,如果商店提供,则添加resetTime 日期对象。这些可以在您的应用程序代码中使用,以采取其他操作或通知用户他们的状态。

    您的/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
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多