I got a simple chat app utilizing socket.io and express framework, below is part of the code:
var app = express.createServer();
var socket = io.listen(app);
var store = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({
secret: 'something',
store: store,
cookie: {
maxAge: 60*60*24*30*1000
}
}));
app.get('/', function(req, res){
socket.on('connection', function(client) {
req.session.ioid = client.sessionId;
req.session.channel = req.param('channel');
req.session.username = req.param('username');
//I want the code below happen just once
res.header('Content-Type', 'text/plain');
res.header('Access-Control-Allow-Origin', '*');
res.send({sid:req.session.id});
});
});
You can see the res.header and res.send in the socket.on closure. Those "res" will execute constantly, and cause error "Can't set headers after they are sent."
I'm looking for a way to make the block-
res.header('Content-Type', 'text/plain');
res.header('Access-Control-Allow-Origin', '*');
res.send({sid:req.session.id});
-happen just once.
app.get('/', function(req, res){
socket.on("connection", function(client) {
req.session.ioid = client.sessionId;
req.session.channel = req.param('channel');
req.session.username = req.param('username');
});
socket.once('connection', function(client) {
//I want the code below happen just once
res.header('Content-Type', 'text/plain');
res.header('Access-Control-Allow-Origin', '*');
res.send({sid:req.session.id});
});
});
Use .once
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With