I've read other questions regarding this error, but I can't see how any of the answers apply to my own case. I've checked the usual culprits - I don't do anything with the response object after calling send and as far as I can tell my callback isn't being called more than once. But no matter what I try I keep getting the error "Can't set headers after they are sent". Here is an example of my code:
var express = require('express');
var ws = require('nodejs-websocket');
var app = express();
var socket = ws.connect("ws://localhost:5000");
var port = 8000;
app.get('/', function(req, res) {
var r = JSON.stringify({
type: "page request",
request: {
url: req.query.url,
app: req.query.app
}
});
socket.on("text", function(str){
console.log(str);
var d = JSON.parse(str);
res.send(d.response.body);
return;
});
socket.sendText(r);
});
app.listen(port, function(){
console.log("Node app is running on port", port);
});
The first request to '/' works like a charm (or so it seems). Every time, however, the second request results in "Can't set headers after they are sent". Maybe I'm not understanding how the callback for the websocket is closing around the res object? Is it constantly referring to the original res object? I would have thought that each time the route was requested the callback would be redefined with the new res object, but maybe I'm wrong?
There are other issues here. If, for example, no response is received from the websocket then the response will never be returned, which is something I plan on addressing. Also, the way the code stands now any second message coming through the websocket could lead to the error, but I'm currently testing on my local machine with one connected client only, and I'm printing all messages to the console and can see that one and only one message is coming through during the request/response lifecycle. Any help is greatly appreciated!