javascript - 当我发送 GET 请求时:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
问题描述
当我尝试向我的函数的 url 发送 get 请求时(在 firebase 项目上,例如:http://project_url.com/api/post/id),此错误显示
(node:1061) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
> at ServerResponse.setHeader (_http_outgoing.js:518:11)
> at ServerResponse.header (/Users/salvatorebramante/beta/functions/node_modules/express/lib/response.js:771:10)
> at ServerResponse.send (/Users/salvatorebramante/beta/functions/node_modules/express/lib/response.js:170:12)
> at ServerResponse.json (/Users/salvatorebramante/beta/functions/node_modules/express/lib/response.js:267:15)
> at /Users/salvatorebramante/beta/functions/handlers/posts.js:70:25
> at processTicksAndRejections (internal/process/task_queues.js:97:5)
> (node:1061) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
该函数返回一个 json,其中包含有关存储在 firebase 云存储中的文档的信息
exports.getPost = (req,res) => {
let postData;
db.doc(`/posts/${req.params.postId}`).get()
.then(doc =>{
if(!doc.exists){
return res.status(404).json({error : 'Post not found'})
}
postData = doc.data();
postData.postId = doc.id;
return db.collection('comments').orderBy('createdAt', 'desc').where('postId','==',req.params.postId).get();
})
.then(data =>{
postId.comments = [];
data.forEach(doc => {
postData.comments.push(doc.data());
})
return res.json(postData);
})
.catch(err =>{
res.status(500).json({ error: err.code });
console.error(err);
});
};
发生错误时,获取请求响应为 404,但我已检查文档 ID 是否正确。我该如何解决?
解决方案
推荐阅读
- python - CouchDB 只写/只读(无编辑)用户
- c - 如何将一串数字解析为整数数组?
- python - 如何计算一个矩阵中向量之间的欧式距离?
- laravel - 如何在 Laravel 中对结果进行分页和排序?
- reactjs - Admob - RNAMobRewardedVideoAdModule 不是抽象的
- android - 从android中的媒体会话中删除活动歌曲
- sql - 函数调用过程给出错误“只能从函数内执行函数和一些扩展存储过程”
- python - 打开函数中给出的 csv 文件
- c - 在 C 中的函数递归中传递无符号数组
- dart - 如何在 Flutter 上更改 BottomNavigationBar 项目的颜色?