0

我有以下代码:

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'

有任何想法吗?我查看了其他帖子是否存在相同的错误。我知道如果我尝试发送响应 2 次会发生这种情况:res.send({...}) 和 res.send({...})。但是,在我的情况下不会发生这种情况。提前致谢

4

1 回答 1

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()"
    }
  }
});

于 2020-05-27T09:12:43.313 回答