Skip to content

Instantly share code, notes, and snippets.

@epadillas
Created July 14, 2013 10:26
Show Gist options
  • Save epadillas/5993856 to your computer and use it in GitHub Desktop.
Save epadillas/5993856 to your computer and use it in GitHub Desktop.
Send cookies for the socket.io handshake (sails.js)
// Send cookies for the socket.io handshake (sails.js)
// Based on https://gist.github.com/jfromaniello/4087861
// Socket.io open ticket (started by jfromaniello):
// https://github.com/LearnBoost/socket.io-client/pull/512
var io = require('socket.io-client');
var request = require('request');
var xhr = require('socket.io-client/node_modules/xmlhttprequest');
var xhrOriginal = require('xmlhttprequest');
var myUrl = 'http://192.168.56.101:1337';
var cookieJar = request.jar();
// From socket.io-client's module 'xmlhttprequest', rewrie its XMLHttpRequest function.
xhr.XMLHttpRequest = function() {
this.XMLHttpRequest = xhrOriginal.XMLHttpRequest;
xhrOriginal.XMLHttpRequest.apply(this, arguments);
this.setDisableHeaderCheck(true); // Allow header modifications.
// Rewrite the 'open' function.
var openOriginal = this.open;
this.open = function(method, url, async, user, password) {
openOriginal.apply(this, arguments);
var header = cookieJar.get({url: myUrl}).map(function(cookie) {
return cookie.name + '=' + cookie.value;
}).join('; ');
this.setRequestHeader('cookie', header);
};
};
// Send the cookie first before attempting to connect via socket-io,
// thus, avoiding the handshake error.
request.post({jar: cookieJar, url: myUrl}, function(err, resp, body) {
var socket = io.connect(myUrl);
socket.on('connecting', function() {
console.log('(II) Connecting to server');
});
socket.on('connect', function() {
console.log('(II) Successfully connected to server');
});
socket.on('error', function(reason) {
console.log('(EE) Error connecting to server: ' + reason);
});
socket.on('disconnect', function(reason) {
console.log('(II) Disconnected from server\n');
});
});
@3emad
Copy link

3emad commented Nov 10, 2013

This is awesome!

@RJTM
Copy link

RJTM commented Feb 7, 2014

TypeError: Object # has no method 'get'

I'm getting this error with request v 2.33.0
How can I fix this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment