首页 > 解决方案 > firebase 函数未以 response.send 终止

问题描述

当满足某些条件时,我试图终止我的功能。但它看起来像函数结束,但控制超出了 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)

标签: firebasegoogle-cloud-firestoregoogle-cloud-functionsfirebase-tools

解决方案


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

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


推荐阅读