首页 > 解决方案 > 当我发送 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 是否正确。我该如何解决?

标签: javascriptnode.jsfirebase

解决方案


推荐阅读