Node.js express中间件的超时问题
我有一个用于令牌验证的中间件。下面是它的外观:Node.js express中间件的超时问题,node.js,express,Node.js,Express,我有一个用于令牌验证的中间件。下面是它的外观: this.checkJwt = jwt({ secret: jwksRsa.expressJwtSecret({ cache: true, rateLimit: true, jwksRequestsPerMinute: 5, jwksUri: process.env.AUTH0_JWKS, }), // Validate the audience and th
this.checkJwt = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: process.env.AUTH0_JWKS,
}),
// Validate the audience and the issuer.
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: ["RS256"],
});
然后我将其应用于我的路线:
app.route(routes.getUserInfo)
.get(checkJwt, this.userController.me);
为什么当我用return语句重写中间件时,它停止工作?像这样:
this.checkJwt = (req, res, next) => {
return jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: process.env.AUTH0_JWKS,
}),
// Validate the audience and the issuer.
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: ["RS256"],
});
};
对于这个中间件的每个请求,我都会遇到超时异常。似乎下一个函数从未触及。我不知道jwt方法是什么-自定义中间件还是只使用jwt包
我还看到您返回jwt调用时没有传递req、res和next:
中间件调用期间执行的结果是[Function]req,res,下一个预期执行的命令-未返回
因此,如果是中间件,请尝试使用以下方式重写它:
const checkJwt = (req, res, next) => {
jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: process.env.AUTH0_JWKS,
}),
// Validate the audience and the issuer.
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: ["RS256"],
})(req, res, next);
};
app.get(routes.getUserInfo, checkJwt, this.userController.me)
但是,如果jwt方法不是中间件,它将返回true或false作为结果:
const checkJwt = (req, res, next) => {
const result = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: process.env.AUTH0_JWKS,
}),
// Validate the audience and the issuer.
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: ["RS256"],
});
// if jwt returns something (:
if (!result) {
return res.status(401).send('Unauthorized');
}
next();
};
app.get(routes.getUserInfo, checkJwt, this.userController.me)
谢谢第一个是为我工作。第二个完全跳过中间件逻辑,每次只调用next。@neustart47因为我不知道什么是jwt方法,我只能假设它返回一些可以处理的东西。但若第一个例子有效,那个么jwt方法似乎是定制中间件。还有一个问题:这意味着jwt{}req,res,next是什么?这个结构意味着什么?这部分jwt{}是方法输入参数,那么这部分req,res,next是什么意思呢?这是一个关于JS的问题,似乎我遗漏了一些东西it@neustart47本例中的jwt{}返回一个函数,该函数在调用中间件时采用相同的参数。但是它也需要调用嵌套函数。啊,我知道了。谢谢!
const checkJwt = (req, res, next) => {
const result = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: process.env.AUTH0_JWKS,
}),
// Validate the audience and the issuer.
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: ["RS256"],
});
// if jwt returns something (:
if (!result) {
return res.status(401).send('Unauthorized');
}
next();
};
app.get(routes.getUserInfo, checkJwt, this.userController.me)