错误:发送后无法设置标头。 RabbitMQ干扰NodeJS响应

时间:2015-05-23 20:50:28

标签: javascript node.js express amqp node-amqp

在http响应之后,我发送了一个使用RabbitMQ(创建频道等)的混乱,然而,服务器正在抱怨"错误:发送后无法设置标头。&#34 ;

以下是代码:

var amqp = require('amqplib');
var when = require('when');

var rabbitmq_conn = amqp.connect('amqp://localhost' );

function push_keystroke_data(session_id, data) {
  var QUEUE_NAME = 'hello';
  var msg = session_id;

  when(rabbitmq_conn.createChannel()).then(function(ch) {
    var ok = ch.assertQueue(QUEUE_NAME, {durable: false});

    ok.then(function(_qok) {
      ch.sendToQueue(QUEUE_NAME, new Buffer(msg));
      console.log(" [x] Sent '%s'", msg);
      ch.close();
    });

  }).ensure(function() {
    conn.close();
  });
}

router.post('/', function(req, res, next) {

  // current session id
  var sid;

  if (req.cookies.papi) {
    sid = req.cookies.papi.session_id;
  } else {
    sid = generate_session_id();
    res.cookie('papi', {session_id: sid}, {maxAge: COOKIE_MAX_AGE});
  }

  res.send(JSON.stringify({ user_id: get_user_id(sid)}));

  var data = process_keystroke_data(req.body);
  push_keystroke_data(sid, data);

});

我假设RabbitMQ在响应之后设置了标题(我还尝试在响应之前发送RabbitMQ消息,但也没有解决任何问题)。

这是堆栈跟踪:

POST /api 500 220.100 ms - 16
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at ServerResponse.header (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/response.js:700:10)
    at ServerResponse.send (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/response.js:154:12)
    at fn (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/response.js:934:10)
    at View.exports.renderFile [as engine] (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/jade/lib/index.js:374:12)
    at View.render (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/view.js:93:8)
    at EventEmitter.app.render (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/application.js:566:10)
    at ServerResponse.res.render (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/response.js:938:7)
    at /Users/mikeecb/Documents/KeyNA/jsbackend/app.js:62:7
    at Layer.handle_error (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/router/layer.js:58:5)

非常感谢任何解决方案或想法。

1 个答案:

答案 0 :(得分:1)

事实证明问题不在于RabbitMQ正在设置标题(这会很奇怪,为什么它会做任何http的东西?)但是在回复&mut received_message_buf后,我试图发送另一个响应,显然是这个问题。