如果调用的函数未在同一文件中定义,为什么我的中间件函数不起作用?
Why does my middleware function not work if its called function is not defined in the same file?
我面临以下问题:
案例 1(工作案例):
文件middleware.ts(中间件实用程序函数库)
import { NextApiRequest, NextApiResponse } from 'next'
import rateLimit from 'express-rate-limit'
export function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: Function) {
return new Promise((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
export const limiter = rateLimit({
keyGenerator: function (req: any) {
return req.headers["x-forwarded-for"] || req.connection.remoteAddress;
}, // Needed because of issue : https://issueexplorer.com/issue/nfriedly/express-rate-limit/254
windowMs: 60 * 1000, // 1 minute
max: 5, // 5 requests per IP
})
文件login.ts
(我的API入口点)
import { NextApiRequest, NextApiResponse } from 'next'
import { limiter, runMiddleware } from '../../lib/middleware'
module.exports = async (req: NextApiRequest, res: NextApiResponse) => {
// Run middlewares
try {
await runMiddleware(req, res, limiter)
} catch {
res.status(500)
res.end(JSON.stringify({errorCode: 'unknown', errorValue: ''}))
return
}
if (req.method === 'POST') {
res.status(200)
res.end(JSON.stringify({errorCode: 'ok', errorValue: ''}))
}
}
在这种情况下,如果我尝试超过 5 次才能达到我的 API,我会收到消息“太多请求...”,这正是我想要的。
案例 2(非工作案例):
文件middleware.ts
(中间件实用程序函数库)
import { NextApiRequest, NextApiResponse } from 'next'
export function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: Function) {
return new Promise((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
文件login.ts
(我的API入口点)
import { NextApiRequest, NextApiResponse } from 'next'
import rateLimit from 'express-rate-limit'
import { runMiddleware } from '../../lib/middleware'
// Run middlewares
try {
const limiter = rateLimit({
keyGenerator: function (req: any) {
return req.headers["x-forwarded-for"] || req.connection.remoteAddress;
}, // Needed because of issue : https://issueexplorer.com/issue/nfriedly/express-rate-limit/254
windowMs: 60 * 1000, // 1 minute
max: 5, // 5 requests per IP
})
await runMiddleware(req, res, limiter)
} catch {
res.status(500)
res.end(JSON.stringify({errorCode: 'unknown', errorValue: ''}))
return
}
if (req.method === 'POST') {
res.status(200)
res.end(JSON.stringify({errorCode: 'ok', errorValue: ''}))
}
我看不出这两种情况之间的差异可以解释为什么在我的第二种情况下它不起作用。有人有解释吗?
提前致谢。
@juliomalves 在评论中给出了答案:
“那是因为你在每个请求上声明并分配值给限制器,每次都会调用 rateLimit。尝试将限制器声明移到处理程序函数之外。”
我面临以下问题:
案例 1(工作案例):
文件middleware.ts(中间件实用程序函数库)
import { NextApiRequest, NextApiResponse } from 'next'
import rateLimit from 'express-rate-limit'
export function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: Function) {
return new Promise((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
export const limiter = rateLimit({
keyGenerator: function (req: any) {
return req.headers["x-forwarded-for"] || req.connection.remoteAddress;
}, // Needed because of issue : https://issueexplorer.com/issue/nfriedly/express-rate-limit/254
windowMs: 60 * 1000, // 1 minute
max: 5, // 5 requests per IP
})
文件login.ts
(我的API入口点)
import { NextApiRequest, NextApiResponse } from 'next'
import { limiter, runMiddleware } from '../../lib/middleware'
module.exports = async (req: NextApiRequest, res: NextApiResponse) => {
// Run middlewares
try {
await runMiddleware(req, res, limiter)
} catch {
res.status(500)
res.end(JSON.stringify({errorCode: 'unknown', errorValue: ''}))
return
}
if (req.method === 'POST') {
res.status(200)
res.end(JSON.stringify({errorCode: 'ok', errorValue: ''}))
}
}
在这种情况下,如果我尝试超过 5 次才能达到我的 API,我会收到消息“太多请求...”,这正是我想要的。
案例 2(非工作案例):
文件middleware.ts
(中间件实用程序函数库)
import { NextApiRequest, NextApiResponse } from 'next'
export function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: Function) {
return new Promise((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
文件login.ts
(我的API入口点)
import { NextApiRequest, NextApiResponse } from 'next'
import rateLimit from 'express-rate-limit'
import { runMiddleware } from '../../lib/middleware'
// Run middlewares
try {
const limiter = rateLimit({
keyGenerator: function (req: any) {
return req.headers["x-forwarded-for"] || req.connection.remoteAddress;
}, // Needed because of issue : https://issueexplorer.com/issue/nfriedly/express-rate-limit/254
windowMs: 60 * 1000, // 1 minute
max: 5, // 5 requests per IP
})
await runMiddleware(req, res, limiter)
} catch {
res.status(500)
res.end(JSON.stringify({errorCode: 'unknown', errorValue: ''}))
return
}
if (req.method === 'POST') {
res.status(200)
res.end(JSON.stringify({errorCode: 'ok', errorValue: ''}))
}
我看不出这两种情况之间的差异可以解释为什么在我的第二种情况下它不起作用。有人有解释吗?
提前致谢。
@juliomalves 在评论中给出了答案:
“那是因为你在每个请求上声明并分配值给限制器,每次都会调用 rateLimit。尝试将限制器声明移到处理程序函数之外。”