[英]How to increase the blocking time period after being rate limited using express-rate-limit in Node js?
[英]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
属性被添加到所有请求中,包括limit
、current
和remaining
请求数,如果商店提供它,还添加一个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.