Skip to content

Instantly share code, notes, and snippets.

@epadillas
Created July 14, 2013 10:26
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
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