Event Emmiter使用express.js返回错误500,它只能在一个事件中获得200个响应

时间:2018-01-13 21:29:48

标签: javascript node.js express eventemitter

在我的项目中,我有一些功能疼痛,会引发一些事件:

const express = require('express');
const EventEmitter = require('events');

/*Initialize Body parsers etc etc*/

const emmiter=new EventEmitter();

const emmitFunctionality=function(message){
  if(message==='hello'){
   return emmiter.emit("ok")
  }
  return emmiter.emit("fail");
}

express.post('/my-route',function(req,res,next){

   emmiter.on('ok',function(){
     res.json({status:true})
   });

   emmiter.on('fail',function(){
     res.json({status:fail})
   });

   emmitFunctionality(req.message);
})

app.listen(80,function(){
  console.log("Listening over port: 80");
});

但是当我尝试执行以下http POST请求时,我遇到了问题:

  

发布http://localhost/my-route -d" {message:' hello'}"

虽然我尝试

  

发布http://localhost/my-route -d" {message:' harem'}"

我收到以下回复:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client<br> &nbsp; &nbsp;at validateHeader (_http_outgoing.js:503:11)<br> &nbsp; &nbsp;at ServerResponse.setHeader (_http_outgoing.js:510:3)<br> &nbsp; &nbsp;at ServerResponse.header (/opt/map/node_modules/express/lib/response.js:767:10)<br> &nbsp; &nbsp;at ServerResponse.send (/opt/map/node_modules/express/lib/response.js:170:12)<br> &nbsp; &nbsp;at ServerResponse.json (/opt/map/node_modules/express/lib/response.js:267:15)<br> &nbsp; &nbsp;at EventEmitter.emmiter.on (/opt/map/src/controllers/panel.js:42:9)<br> &nbsp; &nbsp;at EventEmitter.emit (events.js:164:20)<br> &nbsp; &nbsp;at module.exports.self.readAllLinesFromXLSXBufferAndProcessWithACallback (/opt/map/src/services/excell.js:41:20)<br> &nbsp; &nbsp;at /opt/map/src/controllers/panel.js:46:16<br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/opt/map/node_modules/express/lib/router/layer.js:95:5)</pre>
</body>
</html>

你们的伙伴们知道这种情况发生的原因以及我将如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您应该检查响应是否已发送标头。这可以通过以下代码完成:

if(!res.headersSent) {
  //send response here
}

因此,在您的代码中,通过/my-route路线生成帖子的部分将为:

express.post('/my-route',function(req,res,next){

   emmiter.on('ok',function(){
     if(!res.headersSent) {
       res.json({status:true})
     }
   });

   emmiter.on('fail',function(){
     if(!res.headersSent) {
      res.json({status:fail})
     }
   });
 emmitFunctionality(req.message);
})