koa jwt验证成功后 next() 但是控制器里面不能返回值

发布于 2022-09-11 16:15:05 字数 2149 浏览 16 评论 0

我在做token验证,验证成功后才能继续拉取数据,但是现在验证成功后控制器里面能拉取数据,却不能返回到客户端 客户端报错404

下面是代码:
1.jwt代码:

const requireAuth = (ctx, next) => {

const token = ctx.request.headers.authorization
console.log('穿过来的token'+token);
if (token) {

jwt.verify(token, jwtSecret, function(err, decoded) {
  if (err) {
    console.log('打印错误'+err.message);
    if (err.name === 'TokenExpiredError') {
      ctx.body={
        status:400,
        msg:'认证码失效,请重新登录!'
      }
    } else {
      ctx.body={
        status:401,
        msg:'认证码失效!'
      }
    }
  } else {
    console.log(decoded);
    if (decoded.username ) {
      next()
    } else {
      ctx.body = '认证失败'
    }
  }
})

} else {

return ctx.body = '请提供认证码!'

}
}

2.控制器里面的代码:
exports.index = async (ctx) => {
console.log(ctx);

console.log('查询银行卡');
const {
    userId
} = ctx.query
console.log(userId)
const bankcards = await BankCard.find({
    userId
})
console.log(bankcards);
if (bankcards) {
  console.log('获取成功');
    ctx.body = {
        status: 200,
        bankcards
    }
} else {
  console.log('获取失败');
    ctx.body = {
        status: 406,
        msg: '获取银行卡失败'
    }
}

}

后端终端提示:
查询银行卡
i828xTq5b6xMPY3eG
(node:13662) [DEP0079] DeprecationWarning: Custom inspection function on Objects via .inspect() is deprecated
--> GET /bankcards?userId=i828xTq5b6xMPY3eG 404 22ms -
[ { userId: 'i828xTq5b6xMPY3eG',

realName: 'xxx',
accountNumber: '62215xxxxxxxxx56030',
bankAddress: 'xxxx',
createdAt: 2017-08-21T07:37:48.828Z } ]

获取成功

客户端console:
GET http://192.168.31.7:3001/bankcards?userId=i828xTq5b6xMPY3eG 404 (Not Found)
request.js?b775:68 errError: Request failed with status code 404
createError.js?2d83:16 Uncaught (in promise) Error: Request failed with status code 404

at createError (createError.js?2d83:16)
at settle (settle.js?467f:18)
at XMLHttpRequest.handleLoad (xhr.js?b50d:77)







如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

说不完的你爱 2022-09-18 16:15:05

请格式化好代码。
粗略看下你都用koa了不用async+await却用expresscallback方式写jwt.verify逻辑?这2种写法不兼容的

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文