Express Rate Limit
Express Rate Limit 是一个为 ExpressJS 框架实现的流控中间件,用来限制某些方法或者 API 的访问。Express Rate Limit 提供了基于内存和 Redis 的存储控制,在分布式环境也可以使用。
使用方法:
import { rateLimit } from 'express-rate-limit'
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: 'draft-7', // draft-6: RateLimit-* headers; draft-7: combined RateLimit header
legacyHeaders: false, // X-RateLimit-* headers
// store: ... , // Use an external store for more precise rate limiting
})
// Apply the rate limiting middleware to all requests
app.use(limiter)
支持多实例:
import { rateLimit } from 'express-rate-limit'
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: 'draft-7', // draft-6: RateLimit-* headers; draft-7: combined RateLimit header
legacyHeaders: false, // X-RateLimit-* headers
// store: ... , // Use an external store for more precise rate limiting
})
app.use('/api/', apiLimiter)
const createAccountLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // Limit each IP to 5 create account requests per `window` (here, per hour)
message:
'Too many accounts created from this IP, please try again after an hour',
standardHeaders: 'draft-7', // draft-6: RateLimit-* headers; draft-7: combined RateLimit header
legacyHeaders: false, // X-RateLimit-* headers
})
app.post('/create-account', createAccountLimiter, (request, response) => {
//...
})
评论