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;
    }
})

查閱的有關文檔

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