gpt4 book ai didi

javascript - 错误 : Can't set headers after they are sent. RabbitMQ 干扰 NodeJS 响应

转载 作者:行者123 更新时间:2023-12-03 10:04:41 25 4
gpt4 key购买 nike

在 http 响应之后,我使用 RabbitMQ 发送困惑信息(创建 channel 等),但是服务器提示“错误:发送后无法设置 header 。”

这是代码:

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 在响应之后设置 header (我也尝试在响应之前发送 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)

任何解决方案或想法将不胜感激。

最佳答案

事实证明,问题不在于 RabbitMQ 设置 header (这很奇怪,为什么它会执行任何 http 操作?),而是在响应 res.send(JSON.stringify({ user_id : get_user_id(sid)}));,我尝试发送另一个响应,这显然是问题所在。

关于javascript - 错误 : Can't set headers after they are sent. RabbitMQ 干扰 NodeJS 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30417455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com