Express标头发送到客户端后无法设置标头

时间:2020-05-27 08:56:56

标签: express mongoose

我有以下代码:

router.post('/:email/addWorkflow', async function (req, res, next) {
  const params = req.params;
  const workflow = req.body;
  const email = params.email;

      User.findOne({ email: email }, function (err, user) {
        if (err) {
          res.status(500).send({
            error: 'Error while querying database'
          });
        } else if (user) {
          const workflows = user.workflows;
          workflows.forEach(wf => {
            if (wf) {
              if (wf.workflowId === workflow.workflowId) {
                res.status(409).send({
                  error: 'Workflow with that id already exists'
                });
              }
            }
          });
          workflows.push(workflow);
          User.updateOne({ email: email }, { $set: { workflows: workflows } }, { upsert: false }, function (err) {
            if (err) {
              res.status(500).send({
                message: 'Error while updating database'
              });
            } else {
              res.status(200).send({
                message: 'Wf added successfully'
              });
            }
          });
        } else {
          res.status(404).send({
            message: 'No such user'
          });
        }
      });
    });
After I make a post with an already existing workflowId, I get the following error: 

    Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
        at ServerResponse.setHeader (_http_outgoing.js:485:11)
        ..........
        at /home/petar/Documents/jsProjects/p/backend/routes/users.js:50:29
        at CoreDocumentArray.forEach (<anonymous>)
        at /home/petar/Documents/jsProjects/p/backend/routes/users.js:47:17
        at /home/petar/Documents/jsProjects/p/backend/node_modules/mongoose/lib/model.js:4915:16
        at /home/petar/Documents/jsProjects/p/backend/node_modules/mongoose/lib/model.js:4915:16
        at /home/petar/Documents/jsProjects/linear-mixed-models/backend/node_modules/mongoose/lib/query.js:4380:11
        [... lines matching original stack trace ...]
        at processTicksAndRejections (internal/process/task_queues.js:76:11) {
      code: 'ERR_HTTP_HEADERS_SENT'

有什么想法吗?我在其他帖子中看到了相同的错误。我了解如果我尝试发送两次响应,即res.send({...})和res.send({...}),就会发生这种情况。但是,就我而言,这不会发生。预先感谢

1 个答案:

答案 0 :(得分:0)

我不确定错误消息指示的是哪行,但是以下循环是我唯一能想到的对代码进行多重响应的地方

workflows.forEach(wf => {
//foreach is looping
  if (wf) {
    if (wf.workflowId === workflow.workflowId) {
      res.status(409).send({
        error: 'Workflow with that id already exists'
      });
      //but I don't think this guy will stop looping after the first "send()"
    }
  }
});