koa-router async 不等待返回结果直接not found

场景:登录接口,当不添加async的时候可以正常访问,添加之后返回Not Found

router.post('login', async (ctx, next) => {
    console.log('login')
    await userService.findUserByName().then((res) => {
        console.log('findUserByName', res)
        ctx.body = res;
    })
});

这是因为添加了中间件没有添加async。使用router.use中间件的函数不管是不是异步的都需要使用async

router.use(async (ctx, next) => {
    if(await check.chenckLogin(ctx)) {
        await next();
    }else {
        ctx.body = check.notLoginResponse;
    }
})

查阅的有关文档

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章