node.js - 如何使用 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> at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/lib/index.js:102:22
<br> at Object.module.exports [as verify] (/Users/luisandrade/code/slothy_/back/node_modules/jsonwebtoken/verify.js:75:12)
<br> at verifyToken (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/lib/index.js:100:13)
<br> at fn (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:746:34)
<br> at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:1213:16
<br> at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:166:37
<br> at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:706:43
<br> at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:167:37
<br> at Immediate._onImmediate (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:1206:34)
<br> at runCallback (timers.js:810:20)
<br> at tryOnImmediate (timers.js:768:5)
<br> at processImmediate [as _immediateCallback] (timers.js:745:5)
</pre>
</body>
</html>
但我想要的是
{
Error: 'Some Error message'
}
任何帮助将不胜感激,谢谢。
解决方案
根据我从文档中了解到的是,您可以传递一个自定义中间件,express
用于错误处理
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401).send('invalid token...');
}
})
推荐阅读
- git - NPM 脚本自动执行包增量和 GIT 推送
- swift - 位置()/偏移()swiftUI的问题
- javascript - Vue:如何从 api 中删除项目
- python - 在python链表的头部插入
- php - 来自 LEFT JOIN 项的排序和分组查询结果
- java - Optaplanner 可以自动添加或删除计划实体吗?
- php - Slim 4 框架动态 PDO 连接使用从主数据库获取的数据库连接信息
- php - 在产品页面上显示超过 1000 克的产品重量(KG)
- javascript - 覆盖 wordpress !important,同时仍然能够使用 javascript 来使用它
- c# - 另一个类 C# WPF 中存在的方法的进度条