首页 > 解决方案 > Koa.js 总是找不到 404

问题描述

我在 Koa 中开发并使用 Firebase 进行消息传递,因为有一个实时数据库。当我想从 firebase 获取消息时,我得到了 Not found,但console.log()它显示了我。

这是我的功能getConversation(消息)

async getConversation(conversationName, callback) {
    var ref = await admin.database().ref(`messages/${conversationName}`)
    await ref.on('value', (snapshot, prevChildKey) => {
        var newPost = snapshot.val()
        let values = Object.values(newPost)
        callback(values)
    })
}

然后我像这样在另一个控制器中调用它

async getMessages(ctx) {
    const id = ctx.params.id

    const nameOfConversation = await ctx.db.Conversation.findById(id)

    await firebaseIndex.fbController.getConversation(nameOfConversation.name, response => {
        console.log(response)
        ctx.body = response //TODO
    })

}

最后,我在路由中调用它。

router.get('/getConversation/:id', middlewares.isAuthenticate, controllers.userConversation.getMessages)

我总是找不到身体。有人知道我该如何解决吗?

标签: node.jsfirebasefirebase-realtime-databasekoakoa-router

解决方案


我解决了。

async getMessages(ctx) {
    const id = ctx.params.id

    const nameOfConversation = await ctx.db.Conversation.findById(id)

    ctx.body = await new Promise((resolve, reject) => {
        firebaseIndex.fbController.getConversation(nameOfConversation.name, async response => {
            resolve(response)
        })
    })
}

ctx.body必须有一个Promise。


推荐阅读