首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用express-jwt发送自定义错误响应?

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

Stack Overflow用户
提问于 2019-11-21 14:12:32
回答 1查看 345关注 0票数 0

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

这是我的验证函数

代码语言:javascript
复制
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']
  });

,这就是我要得到的

代码语言:javascript
复制
<!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>

但我想要的是

代码语言:javascript
复制
{
    Error: 'Some Error message'
}

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

EN

回答 1

Stack Overflow用户

发布于 2019-11-21 14:19:34

根据我从文档中了解到的情况,您可以使用express传递一个自定义中间件以进行错误处理。

代码语言:javascript
复制
  app.use(function (err, req, res, next) {
     if (err.name === 'UnauthorizedError') {
     res.status(401).send('invalid token...');
     }
    })

文献参考

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58976936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档