2017-12-18 152 views
2

我试图让我从我的neo4j数据库中保存idsFromMongo并搜索mongodb中的这些id以返回我想要的对象。它工作1次,但然后我的服务器崩溃,并返回错误发送后无法设置标题。他们设置后不能设置标题

这是我的代码:

routes.get('/advertisements/recommended/:brand', function(req, res) { 
    res.contentType('application/json'); 

    var brandFromUrl = req.params.brand; 
    var advertisementIds = []; 

    Advertisement.find({'car.brand': brandFromUrl}) 
    .then(function (ads) { 
     // res.status(200).json(ads); 
     ads.forEach(function (record) { 
     console.log('ids: ' + record._id) 
     session 
      .run("MERGE(a:Advertisement {idFromMongo: {idParam}, brand: {brandParam}}) WITH a MATCH(b: Advertisement {brand: {brandParam}}) MERGE(a)-[:SHARED_BRAND]->(b)", {idParam: record._id.toString(), brandParam: brandFromUrl}) 
      .then(function(result) { 
      session 
       .run("MATCH (n:Advertisement{brand: {brandParam}}) RETURN (n)", {brandParam: brandFromUrl}) 
       .then(function(result) { 
       result.records.forEach(function(record){ 
        advertisementIds.push(record._fields[0].properties.idFromMongo); 
       }); 
       Advertisement.find({ 
        '_id': { $in: advertisementIds} 
       }, function(err, docs){ 
        res.status(200).json(docs); 
       }) 
      }) 
     }) 
     }); 
    }) 
    .catch((error) => { 
     res.status(400).json(error); 
    }); 
}); 

这是我的错误:

Error: Can't set headers after they are sent. 
    at validateHeader (_http_outgoing.js:494:11) 
    at ServerResponse.setHeader (_http_outgoing.js:501:3) 
    at ServerResponse.header (c:\dev\individueel-project\individueel-database\node_modules\express\lib\response.js:767:10) 
    at ServerResponse.send (c:\dev\individueel-project\individueel-database\node_modules\express\lib\response.js:170:12) 
    at ServerResponse.json (c:\dev\individueel-project\individueel-database\node_modules\express\lib\response.js:267:15) 
    at c:\dev\individueel-project\individueel-database\api\advertisement.routes.v1.js:70:35 
    at model.Query.<anonymous> (c:\dev\individueel-project\individueel-database\node_modules\mongoose\lib\model.js:4046:16) 
    at c:\dev\individueel-project\individueel-database\node_modules\kareem\index.js:273:21 
    at c:\dev\individueel-project\individueel-database\node_modules\kareem\index.js:131:16 
    at _combinedTickCallback (internal/process/next_tick.js:131:7) 
    at process._tickCallback (internal/process/next_tick.js:180:9) 
+0

每个请求只能发送一次回复。但是在你的代码中,你正在发送多个响应来进行声明 – ZeroCho

回答

0

这里的问题是,你正在执行一个数组,并放入数组您发送的响应。所以,最终它会多次发送回复,但只有第一次才会起作用,之后会引发错误。 为了解决这个问题,你应该在数组中的所有承诺完成之后回答请求(Promise.all),或者如果你不需要等到整个数组完成,那么检查你是否已经做出了回应并且不做它再次。