首页 > 解决方案 > 对路由器等 API 请求使用速率限制

问题描述

  1. 我似乎无法将速率限制嵌入到下面的路由器请求中:

  2. 我可以看到如何创建速率限制。

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

const app = express();
const port = 3000;

//create a request limit  object
const limiter = rateLimit({
  windowsMs: 15 * 60* 1000, //15* 60 seconds = 15min
  max:100,
})

//apply the request limit to all request
//middle ware
app.use(limiter); //app.use("/api/", apiLimiter); to only use with request to /api/
app.get('/', limiter, (req,res)=>res.send("hellow World"));
app.listen(port,()=> console.log('Example app on port $(port)|'))
  1. 认为答案如下 - 但总体上看起来并不正确 - 任何想法如何使以下工作?
app.get('/',limiter,(req, res, next)=>{
  res.redirect('/plants'); //plantblogs
});

app.get('/about',limiter,(req, res, next)=>{
    //send file to a browser
    res.render('about', {title: 'About Us' });
});

//redirect 301
app.get('about-me',limiter,(req,res,next)=>{
  res.redirect('./about');
});

//blogroutes
app.use('/plants','plantRoutes',limiter,(req,res,next)); //scope all blog urls to blogrouter

//error logging on server to file
app.use((err,req,res,next)=>{
  let error ="";
  error+=err.code+\r\t;
  error+=err.message+\n;
  fs.writefile('./docs/plantErrors.txt', error,(err,data)=>{ //fs is async function so must use next
    next(err);
  });
  1. 这对你们来说是正确的吗?

标签: apirequestlimitrouter

解决方案


推荐阅读