当我尝试将获取请求发送到函数的url时(在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);
});
};
虽然发生错误,但get请求响应为404,但是我检查了文档ID是否正确。我该如何解决?