首页 > 解决方案 > 如何使用 express-jwt 发送自定义错误响应?

问题描述

我想知道如何在 express-jwt 未经授权时更改它的响应,我尝试使用错误处理程序但它不起作用。

这是我的验证功能

const checkJwt = jwt({
secret: jwksRsa.expressJwtSecret({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 5,
      jwksUri: `https://dev-88888.com/.well-known/jwks.json`
  }),
 audience:'https://dev-******.com/api/v2/',
    issuer: `https://dev000000.com/`,
    algorithms: ['RS256']
  });

这就是我得到的

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>UnauthorizedError: invalid token
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/lib/index.js:102:22
            <br> &nbsp; &nbsp;at Object.module.exports [as verify] (/Users/luisandrade/code/slothy_/back/node_modules/jsonwebtoken/verify.js:75:12)
            <br> &nbsp; &nbsp;at verifyToken (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/lib/index.js:100:13)
            <br> &nbsp; &nbsp;at fn (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:746:34)
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:1213:16
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:166:37
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:706:43
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:167:37
            <br> &nbsp; &nbsp;at Immediate._onImmediate (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:1206:34)
            <br> &nbsp; &nbsp;at runCallback (timers.js:810:20)
            <br> &nbsp; &nbsp;at tryOnImmediate (timers.js:768:5)
            <br> &nbsp; &nbsp;at processImmediate [as _immediateCallback] (timers.js:745:5)
        </pre>
    </body>
</html>

但我想要的是

{
    Error: 'Some Error message'
}

任何帮助将不胜感激,谢谢。

标签: node.jsoauthexpress-jwt

解决方案


根据我从文档中了解到的是,您可以传递一个自定义中间件,express用于错误处理

  app.use(function (err, req, res, next) {
     if (err.name === 'UnauthorizedError') {
     res.status(401).send('invalid token...');
     }
    })

文档参考


推荐阅读