错误:发送邮件后无法设置标头。在ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:356:11)

时间:2017-12-22 06:02:32

标签: node.js mongodb

由于错误,我面临问题,即

  

发送后无法设置标头

实际上,我正在查询我的MongoDB。

Test.aggregate([
                {$match: {'ownerid': req.body.ownerid}},
                {$unwind: '$groupname'},
                {$project: {_id:1, groupname :"$groupname",}}
            ], function(error, data){
                if(error) {
                    console.log(error);
                } else {
                    //It will return Two group id.
                    for(var i=0; i<data.length; i++){

                        //These are the variables for my custom function which can update my query on another table
                        var primaryfilter = {'userid': req.body.ownerid};
                        var secondaryfilter = { "groupowned" : { 'groupid': data[i]._id, 'groupname': data[i].groupname } };
                        var activityname = 'Group Owned';
                        updater(req, res, Test1, primaryfilter, secondaryfilter, activityname);
                    }
                }
            });

这一个是我的更新程序功能:

var updater = function(req, res, CollectionName, primaryfilter, secondaryfilter, activityname){
    CollectionName.update(primaryfilter, {$push: secondaryfilter}, function(error2, result){
        if (error2) {
            res.send({"error":"true", "status":"500", "message":"Oops! Some error occurred while updating the "+activityname+" on Post"});
        } else {
            res.send({"error":"false", "status":"201", "message":"Successfully Updated "+activityname+" on Post"});
        }
    });

};

实际上,我想从测试集合中获取组ID并更新我的辅助表上的所有这些ID,即Test1 我知道这个错误生成由于循环。任何人建议我如何解决这个问题。任何帮助表示赞赏

2 个答案:

答案 0 :(得分:2)

当您尝试为给定请求发送多个响应时,会看到您看到的错误。

您正在使用res.send()来呼叫updater()。并且,您在updater()循环内调用for,这意味着您多次调用它。

因此,您最终会在同一请求中多次调用res.send()。这就是导致你看到错误的原因。每个请求只能拨打res.send()一次。

您可能需要做的是累积所有.update()次调用的结果,然后在完成所有操作后发送一个响应。但是,你必须决定你想要的行为。你想发送什么样的回应?像这样的一系列对象?

{"error":"false", "status":"201", "message":"Successfully Updated "+activityname+" on Post"}

还是其他什么?而且,如果您的某个请求出现错误,您希望响应是什么?

由于这是mongodb,您可能希望使用mongodb内置的promise Promise.all()知道所有.update()调用何时完成。

这是接近它的一种方法:

Test.aggregate([
    {$match: {'ownerid': req.body.ownerid}},
    {$unwind: '$groupname'},
    {$project: {_id:1, groupname :"$groupname",}}
], function(error, data){
    if(error) {
        console.log(error);
    } else {
        //It will return Two group id.
        let promises = [];
        for(var i=0; i<data.length; i++){

            //These are the variables for my custom function which can update my query on another table
            var primaryfilter = {'userid': req.body.ownerid};
            var secondaryfilter = { "groupowned" : { 'groupid': data[i]._id, 'groupname': data[i].groupname } };
            var activityname = 'Group Owned';
            promises.push(updater(Test1, primaryfilter, secondaryfilter, activityname));
        }
        Promise.all(promises).then(function(results) {
            res.json(results);
        }).catch(err => {
            console.log(err);
            res.sendStatus(500);
        })
    }
});


function updater(CollectionName, primaryfilter, secondaryfilter, activityname){
    return CollectionName.update(primaryfilter, {$push: secondaryfilter}).then(function(result) {
        return {"error":"false", "status":"201", "message":"Successfully Updated "+activityname+" on Post"};
    }).catch(function(err) {
        return {"error":"true", "status":"500", "message":"Oops! Some error occurred while updating the "+activityname+" on Post"};
    });
};

答案 1 :(得分:0)

当您尝试向给定请求发送多个响应时,会看到您看到的错误。试试这段代码:

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.dropdown-submenu {
    position: relative;
}

.dropdown-submenu .dropdown-menu {
    top: 0;
    left: 100%;
    margin-top: -1px;
}
</style>
</head>
<body>
   
<div class="container">
  <h2>Multi-Level Dropdowns</h2>
  <p>In this example, we have created a .dropdown-submenu class for multi-level dropdowns (see style section above).</p>
  <p>Note that we have added jQuery to open the multi-level dropdown on click (see script section below).</p>                                        
  <div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorials
    <span class="caret"></span></button>
    <ul class="dropdown-menu">
      <li><a tabindex="-1" href="#">HTML</a></li>
      <li><a tabindex="-1" href="#">CSS</a></li>
      <li class="dropdown-submenu">
        <a class="test" tabindex="-1" href="#">New dropdown 1 <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
          <li class="dropdown-submenu">
            <a class="test" href="#">Another dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#">3rd level dropdown</a></li>
              <li><a href="#">3rd level dropdown</a></li>
            </ul>
          </li>
        </ul>
      </li>
      <li class="dropdown-submenu">
        <a class="test" tabindex="-1" href="#">New dropdown 2 <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
          <li class="dropdown-submenu">
            <a class="test" href="#">Another dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#">3rd level dropdown</a></li>
              <li><a href="#">3rd level dropdown</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>

<script>
$(document).ready(function(){
  $('.dropdown-submenu a.test').on("click", function(e){
    $(this).next('ul').toggle();
    e.stopPropagation();
    e.preventDefault();
  });
});
</script>

</body>
</html>