【发布时间】: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