简体   繁体   English

UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头

[英]UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clien

I get error: "UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client", guessing that the problem is with promises, but I don't understand how to fix it.我收到错误:“UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client”,猜测问题出在 Promise 上,但我不明白如何解决。

How do I fix my code to avoid this error, but keep the logic and work with the database?如何修复我的代码以避免此错误,但保留逻辑并使用数据库?

router.post("/addNote", (req, res) => {
    let currentTime = new Date();
    currentTime.setUTCHours(currentTime.getUTCHours() + 3);
    const post = new PostModel({
        title: req.body.inputHeader,
        text: req.body.inputText,
        author: req.body.author,
        createdAt: currentTime
    });

    post.save().then(() => {
        res.json({status: "saved"});
    })});

router.get("/getNotes", (req, res) => {
    PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) => {
        if (err)
            res.json(err);
        res.json(notes);
    });
});


router.delete("/deleteNote/:id", (req, res) => {
    PostModel.deleteOne(
        {
            _id: req.params.id
        }
    ).then((notes) => {
        if (notes)
            res.json({status: "deleted"});
        res.json({status: "error while deleting"});
    });
});


router.put("/updateNote/:id", (req, res) => {
    PostModel.findByIdAndUpdate(
        req.params.id,
        {
            $set: req.body
        },
        err => {
            if (err)
                res.send(err);
            res.send({status: "updated"})
        }
    ).then((notes) => {
        if (notes)
            res.json({status: "update"});
        res.json({status: "error while updating"});
    });
});


router.get("/getNote", (req, res) => {
    PostModel.findOne({ _id: req.params.id}).then(post => {
        if (!post){
            res.send({error: "not found"});
        } else {
            res.json(post)
        }
    });
});

router.post("/authorize", (req, res) => {
    // bcrypt.hash ("", saltRounds, (err, hash) => {
    //     console.log(hash);
    // });

    let resultAuthorization = false;
    if (req.body.login === authorization.login) {
        resultAuthorization = bcrypt.compareSync(req.body.password, authorization.password);
    }

    if (resultAuthorization)
        res.json({statusAuthorization: "correct"});
    res.json({statusAuthorization: "incorrect"});
});

module.exports = router;

The problem is that you are calling res.json several times in one handler.问题是您在一个处理程序中多次调用res.json When calling it a second time a response has already been sent so you can not send another response.当第二次调用它时,已经发送了响应,因此您无法发送另一个响应。

As tkausl already pointed out you are missing else s so that res.json is being called once.正如 tkausl 已经指出的那样,您缺少else ,因此res.json被调用一次。

You need to change your handlers similar to the /getNote handler.您需要更改类似于/getNote处理程序的处理程序。

The handler for the endpoint deleteNode/:id for example has to be changed to this:例如,端点deleteNode/:id的处理程序必须更改为:

router.delete("/deleteNote/:id", (req, res) => {
  PostModel.deleteOne(
    {
       _id: req.params.id
    }
  ).then((notes) => {
    if (notes)
      res.json({status: "deleted"});
    else
      res.json({status: "error while deleting"});
  });
});

This else also needs to be added in /getNotes and /authorize .这个else也需要添加到/getNotes/authorize中。

The reason is you're trying to send a response more than once.原因是您尝试多次发送响应。 Once the response is returned, if the program sends a response again, this error occurs.一旦返回响应,如果程序再次发送响应,就会出现这个错误。 The reason for the problem is that you do not return the current function after the if condition.出现问题的原因是您在 if 条件之后没有返回当前的 function。 Let me explain with some codes让我用一些代码来解释

router.get("/getNotes", (req, res) => {
    PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) => {
        if (err) {
            res.json(err);
            console.log('We encountered an error and sent the error as a response. But our function still continue...');
        }
        res.json(notes);
        console.log('We tried to sent successfull response but function still continue');
    });
});

So after the response, you should end the function or make sure that you do not call any other response function in the ongoing code stream/flow.因此,在响应之后,您应该结束 function 或确保在正在进行的代码流/流中不调用任何其他响应 function。 Lets fix your code.让我们修复您的代码。

router.get("/getNotes", (req, res) => {
    PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) => {
        if (err) {
            return res.json(err);
            // It is not will be continued because the function returned with response.
        }
        return res.json(notes);
        console.log('No console output')// It is will not be called because function returned.
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 (节点:23)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 - (node:23) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 错误:错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 - error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头 -error - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client -error 这是我收到的错误错误 [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - this is the error i m getting Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 错误:[ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头,获取错误 - Error: [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, fetch error 错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头(多个数据条目) - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client (multiple data entries) 发布请求:错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头 - Post request: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client express 错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 - express Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client res.redirect 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头 - res.redirect Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 两个发送响应的问题:错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头 - Problem with two send responses: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM