始终等待 findOne returns 未找到 (404)

Await on findOne returns not found (404) all the time

下面的代码 returns 始终找不到 (404)。但控制台按预期记录数据。 我正在使用 Node、Koa 和 Mongoose。

server.js

const Koa = require('koa');
const bodyparser = require('koa-bodyparser');
const UserRoutes = require('./router/user.routes');
const TrustRoutes = require('./router/trust.routes');
const auth = require('./middleware/auth');
const app = new Koa();

require('dotenv').config();
require('./db');

app.use(bodyparser());

app.use(auth);

app.use(
   TrustRoutes.routes()
).use(TrustRoutes.allowedMethods());

app.use(
   UserRoutes.routes()
).use(UserRoutes.allowedMethods());

app.listen(process.env.PORT || 3000);

trust.routes.js

const router = new Router({
    prefix: '/trust'
});


router.get('/:trustId', async (ctx,next) => {
    let id = ctx.params.trustId;
    let trust = await Trust.findById(id);
    console.log(trust);
    ctx.response.body = {
        status: true,
        message: 'Trust info',
        data: trust
    };
    console.log('trust info');
    next();
});

module.exports = router

控制台记录以下详细信息

{
  _id: new ObjectId("61ed34100ebd7c8fbdbef596"),
  name: 'new trust',
  description: 'match',
  contact: { email: 'gmail@gmail.com', phone: '90334' },
  isActive: true,
  createdAt: 2022-01-23T10:55:12.866Z,
  updatedAt: 2022-01-23T10:55:12.866Z,
  __v: 0
}
trust info

和中间件(我怀疑在这里)

require('dotenv').config();
const jwt = require("jsonwebtoken");
const User = require("../models/user")

const except = [
    '/user/login'
];

const verifyToken = async (ctx, next) => {

if (except.indexOf(ctx.request.path) >= 0) return next();

let  token = (
    ctx.request.body.token || ctx.request.query.token ||
    ctx.request.headers["authorization"]
);

if (!token) {
    ctx.response.status = 403;
    ctx.body = {
        status: false,
        message: 'Unauthorized'
    }
    return;
}
token = token.replace(/^Bearer\s+/,'');
try {
    const decoded = jwt.verify(token, process.env.TOKEN_KEY);
    const user = await User.findOne({
        email: decoded.username
    },{password: 0});
    ctx.request.user = user;
} catch (err) {
    ctx.response.status = 403;
    ctx.body = {
        status: false,
        message: 'Unauthorized'
    }
    return;
}
next();
};
module.exports = verifyToken;

我知道这里有些东西不正确但很难理解,因为这是我第一次使用带有中间件的异步和 koa,请帮我解决这个问题。

邮递员

您没有从 router-file 中导出任何内容。为了使用

app
.use(TrustRoutes.routes())
.use(TrustRoutes.allowedMethods());

您需要从 TrustRoutes 文件中导出 koa-router:

const router = new Router({
    prefix: '/trust'
});

router.get('/:trustId', async (ctx,next) => {
    // ...
});

module.exports = router;

除此之外,当使用 async 处理程序时,您需要 return next 或 await(参见 https://github.com/ZijianHe/koa-router/issues/476):

router.get('/:trustId', async (ctx,next) => {
        // ...
    return next(); // or await next();
});

我错过了 return next() 在 auth js 中间件中。 将 next(); 更新为 return next() 后,它就可以工作了。

const verifyToken = async (ctx, next) => {
    .....
    return next();
};