我正在创建一个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
});
})发布于 2021-02-24 22:14:23
文档引用了一个Request API
将
req.rateLimit属性添加到具有limit、current和remaining请求数的所有请求中,如果存储区提供该属性,还会添加一个resetTimeDate对象。可以在您的应用程序代码中使用它们来执行其他操作或通知用户它们的状态。
您的/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
});https://stackoverflow.com/questions/62711905
复制相似问题