firebase - 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)
解决方案
我在这里猜测 - 但看起来如果要执行第一个条件,那么您将发送响应并且代码将继续运行并发送进一步的响应。
为什么不尝试在最后设置一个 res,然后使用条件来构建有效负载并查看它是否有效?
推荐阅读
- java - 使用 Jackson 库动态处理请求参数
- reactjs - 如何在不使用输入标签的情况下获取文件对象
- node.js - 警告代码=H27 desc="客户端请求中断" | 主页
- javascript - 如何使对象在 p5.js 中以随时间减少的间隔出现
- angular - 根据行的属性为行指定颜色
- pine-script - input.options 另一个输入的参数
- google-bigquery - ODBC excel BigQuery 连接器是否支持新的 M1 mac?
- wix - WiX - 安装到用户选择安装其余安装的驱动器根目录上的文件夹
- javascript - 使用 forEach 循环 / event.Target 属性的目标输入和 nextElementSibling - JavaScript
- mysql - 在 SQL 中结合 Join 查询和 Where 条件查询