2017-04-26 116 views
0

我试图在我的代码中查找错误,而其他主题没有任何结果。发送后无法设置标题

有app.js代码,其包含来自快车模块get方法:

app.get('/notes', notesController.all); 

有notesController.js代码,其中出口到app.js create方法:

exports.all = function (req, res) { 
    Notes.all(function(err, docs){ 
     if(err){ 
      console.log(err); 
      return res.sendStatus(500); 
     } 
     res.send(docs); 
    }) 
}; 

model此编码:

​​

应用程序崩溃与这个错误:

process.nextTick(function() { throw err; }); 
          ^

Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11) at ServerResponse.header (O:\OGPI6\node_modules\express\lib\response.js:725:10) at ServerResponse.json (O:\OGPI6\node_modules\express\lib\response.js:253:10) at ServerResponse.send (O:\OGPI6\node_modules\express\lib\response.js:158:21) at O:\OGPI6\controllers\notes.js:9:13 at O:\OGPI6\models\notes.js:6:9 at handleCallback (O:\OGPI6\node_modules\mongodb\lib\utils.js:120:56) at O:\OGPI6\node_modules\mongodb\lib\cursor.js:860:16 at handleCallback (O:\OGPI6\node_modules\mongodb-core\lib\cursor.js:171:5) at setCursorDeadAndNotified (O:\OGPI6\node_modules\mongodb-core\lib\cursor.js:505:3)

在我的脑海里唯一的错误,在回调函数“控制器”:

if(err){ 
      console.log(err); 
      return res.sendStatus(500); 
     } 
     res.send(docs); 

但我认为,当发生错误,必须终止函数并返回sendStatus(500),但登录后它尝试返回的控制台中的错误res.send(docs),然后应用程序崩溃,因为它正在发送第二个标头。它看起来很好,但没有工作。任何人都可以指出我失败的方式吗?

+1

您是否认为''exports.all'方法可能会多次触发回调。你有没有试图在回调开始时放置一个'console.log'? –

+0

我同意@BenjiLees,它看起来像回调被召唤两次。 – robertklep

回答

1

使用“下一个”参数中的中间件进行明确知道,这个中间件的目的是完成并没有进一步的需要执行的代码。

exports.all = function (req, res, next) { 
    Notes.all(function(err, docs){ 
     if(err){ 
      console.log(err); 
      res.sendStatus(500); 
      return next(); 
     } 
     res.send(docs); 
    }) 
}; 

返回后执行代码可能是由于异步性质。

您也可以使用else块。

exports.all = function (req, res, next) { 
     Notes.all(function(err, docs){ 
      if(err){ 
       console.log(err); 
       res.sendStatus(500); 

      } 
      else res.send(docs); 
     }) 
    }; 
+1

发送回应_and_ calling'next'都不是一个好主意,因为next可能会让Express将控制权交给另一个也可能发回响应的请求处理程序(或最终的“找不到”处理程序)。 – robertklep

0

更改代码

if(err){ 
    console.log(err); 
    return res.status(500).send(err); 
} 
res.send(docs); 
相关问题