【问题标题】:How to limit express API request by pricing plan如何通过定价计划限制快速 API 请求
【发布时间】:2021-10-18 03:39:18
【问题描述】:

我正在构建一个带有定价计划的公共 API。 我想限制对每个帐户及其计划的 API 请求。 我使用 NodeJS 和 ExpressJS

这些代码无法正常运行,返回数据后我无法 next()。这个中间件怎么解决?

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

const freePlan = rateLimit({
    windowMs: 1 * 60 * 1000,
    max: 5,
    message: {
        error: "Try again after 1 minute"
    }
})

const premiumPlan = rateLimit({
    windowMs: 1 * 60 * 1000,
    max: 30,
    message: {
        error: "Try again after 1 minute"
    }
})

function limiter(req, res, next ) {
    switch (req.body.plan) {
        case "free":
            return freePlan
            break;
    
        case "big":
            return premiumPlan
            break;
    
        default:
            break;
    }
    next();
}

module.exports = limiter;

const express = require('express');
const limiter = require("../middlewares/limiter");
const router = express.Router();

router.get('/', limiter, async (req, res) => {
    res.send('OK');
})

module.exports = router;

【问题讨论】:

  • 我从来没有使用过express-rate-limit,但从代码的角度来看,我认为您应该在限制器中间件中调用freePlanpremiumPlan 函数。

标签: javascript node.js api express express-rate-limit


【解决方案1】:

这是我从github 找到的答案并在这里分享..

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

function isPremium(req) {
  //... your logic to return true false based on premium plan or not
}

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  // see https://github.com/nfriedly/express-rate-limit#max
  max: function(req, res) {
    if (isPremium(req)) {
      return 30;
    }
    return 5;
  }
});

//  apply to all requests
app.use(limiter);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2017-03-03
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多