【问题标题】:firebase function is not terminating with response.sendfirebase 函数未以 response.send 终止
【发布时间】:2021-09-04 12:07:35
【问题描述】:

我正在尝试在满足某些条件时终止我的功能。但它看起来像函数结束,但控件超出了 response.send 并且失败并出现异常 “错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头”

为什么“res.status(400).send”不存在,需要什么退出?

export const getAssessment = functions.https.onRequest(async (req, res) => {
    return cors(req, res, async () => {
        console.log("getAssessment - start");
        const data = req.body;
        const db_fs = admin.firestore();
        const userId = data.userId;
        const bookingDocId = data.bookingDocId;
        console.log("userId " + userId + " bookingDocId " + bookingDocId);

        if (!userId || !bookingDocId) {
            console.error("'userId  or bookingDocId is missing");
            return res.status(400).send({ message: 'userId or bookingDocId is missing' });
        }

        var bookingRef = await db_fs
            .collection("/bookings")
            .doc(bookingDocId)
            .get();

        if (!bookingRef.exists) {
            console.error('No document found with ' + bookingDocId);
            return res.status(400).send({ message: 'No document found with ' + bookingDocId });
        }
        try {
            var reportRef = db_fs.collection("/bookings/" + bookingDocId + "/reports");
            var allReportSnapShot = await reportRef.get();
            let reports = [];
            allReportSnapShot.forEach(report => {
                reports.push(report.data());
            });
            console.log("total reports " + reports.length);
            console.log("getAssessment - end");
            res.status(200).send(reports);
        } catch (error) {
            res.status(500).send({ message: 'failed', data: error });
        }
    })
});

日志:

i  functions: Beginning execution of "us-central1-getAssessment"
>  getAssessment - start
!  functions: The Cloud Firestore emulator is not running, so calls to Firestore will affect production.
>  userId 34344 bookingDocId uMMItjSf7h5lAXcHqtL
>  No document found with uMMItjSf7h5lAXcHqtL
i  functions: Finished "us-central1-getAssessment" in ~1s
>  total reports 0
>  getAssessment - end
>  (node:20560) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
>      at ServerResponse.setHeader (_http_outgoing.js:561:11)

【问题讨论】:

  • 乍一看,似乎没有什么明显的东西会导致这样的错误。目前尚不清楚您是否使用 TypeScript 编写函数,但如果是,请记住您需要在运行模拟器之前重新编译函数。当您使用 res.end() 或其变体时,执行您的云函数的实例不会立即终止。相反,状态设置为“空闲”准备处理更多请求,或者如果空闲时间过长则终止。这意味着函数不只是退出,而且它已经完成,因此不必为每个请求启动实例。

标签: firebase google-cloud-firestore google-cloud-functions firebase-tools


【解决方案1】:

我在这里猜测 - 但看起来如果要执行第一个条件,那么您将发送响应,代码将继续运行并发送进一步的响应。

您为什么不尝试在最后设置一个 res,并使用您的条件来构建有效负载并查看它是否有效?

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 1970-01-01
    • 2020-09-15
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多