在我的项目中,我有一些功能疼痛,会引发一些事件:
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> at validateHeader (_http_outgoing.js:503:11)<br> at ServerResponse.setHeader (_http_outgoing.js:510:3)<br> at ServerResponse.header (/opt/map/node_modules/express/lib/response.js:767:10)<br> at ServerResponse.send (/opt/map/node_modules/express/lib/response.js:170:12)<br> at ServerResponse.json (/opt/map/node_modules/express/lib/response.js:267:15)<br> at EventEmitter.emmiter.on (/opt/map/src/controllers/panel.js:42:9)<br> at EventEmitter.emit (events.js:164:20)<br> at module.exports.self.readAllLinesFromXLSXBufferAndProcessWithACallback (/opt/map/src/services/excell.js:41:20)<br> at /opt/map/src/controllers/panel.js:46:16<br> at Layer.handle [as handle_request] (/opt/map/node_modules/express/lib/router/layer.js:95:5)</pre>
</body>
</html>
你们的伙伴们知道这种情况发生的原因以及我将如何解决这个问题吗?
答案 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);
})