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

我在做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)







阅读 3.3k
1 个回答

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题