Created
July 14, 2013 10:26
-
-
Save epadillas/5993856 to your computer and use it in GitHub Desktop.
Send cookies for the socket.io handshake (sails.js)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); | |
}); | |
}); |
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
This is awesome!