【问题标题】:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client -error错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头 -error
【发布时间】:2021-08-20 08:45:05
【问题描述】:

我正在尝试将页面重定向到另一个页面。当我第一次发送帖子请求时它工作正常,但从第二个帖子请求它给了我这个错误。

错误 [ERR_HTTP_HEADERS_SENT]:发送后无法设置标头 给客户

每次我发送 post 请求时,它都会给我一个错误。

这是代码

const find_doctor_and_update =(a , p) => {
console.log(a)
patients.findOneAndUpdate({name : a} , { $push :{ patients : p } } , {new : true})
.then(data => {
        return data;
})
.catch(err => {
    console.log(err);
}) };


router.post('/upload', authorize,  upload.single('avatar'), (req, res) => {
    console.log(req.body)
    var pname = req.session.userid
    patient_detail.image_name = `${unique_id}-${req.file.originalname}`;
    patient_detail.pid = req.body.pid;
    patient_detail.name = req.body.name;
    patient_detail.age = req.body.age;
    patient_detail.bg = req.body.bg;
    prediction_file.stdin.write(`${unique_id}-${req.file.originalname}\n`);
    prediction_file.stdout.on('data', (output) => {
        if(output == 0){
            patient_detail.class = output;
            console.log('the output is here')

            find_doctor_and_update(pname, (patient_detail))
            .then(data => {
                console.log(data);
                return res.redirect(`/viewpatient/${patient_detail.pid}`);
                
            })
            .catch(err => {
                 //this is the line where i get the error second time when I do post request
                console.log(err);
            })
        }
        console.log(`stdout: ${output}`);
    }) 
})
module.exports = router;

【问题讨论】:

  • 您能向我解释一下流程吗...我看到您没有返回任何承诺,但您仍在使用“find_doctor_and_update”的“then”块。这怎么没有给你任何错误?
  • 是的,当我删除“then”块时,它显示另一个错误,即未处理承诺
  • 流程是 -> 当发送 post 请求时,它会将 body 存储在 patient_detail 中。然后它转到子进程预测文件,然后当返回结果时,它转到“find_doctor_and_update”函数来更新数据库,然后返回更新的数据。如果函数没有错误,则重定向到另一个页面
  • 这就是我不明白的原因。您没有在“find_doctor_and_update”中返回任何承诺,但“then”块对您有用。另外,每次您从邮递员发出帖子请求时,您是否能够看到来自“console.log(a)”的控制台消息——“find_doctor_and_update”中的第一行??
  • 是的,我可以看到

标签: javascript node.js mongodb express


【解决方案1】:

我弄错了。我试图将输出函数“prediction_file.stdout”放在 post 方法中。由于它正在循环返回,即使我尝试返回它也没有返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-26
    • 2018-09-19
    • 2020-09-22
    • 2023-01-19
    • 2021-02-26
    • 2019-09-28
    • 2019-12-25
    相关资源
    最近更新 更多