如何使用express-jwt发送自定义的错误响应?

时间:2019-11-21 14:12:32

标签: node.js oauth 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'
}

谢谢您的任何帮助。

1 个答案:

答案 0 :(得分:1)

根据我对文档的了解,您可以使用express传递自定义中间件来进行错误处理

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

Documentation Reference