Skip to content

Instantly share code, notes, and snippets.

@runspired
Forked from jfromaniello/gist:4087861
Last active August 29, 2015 14:20
Show Gist options
  • Save runspired/8780d2405d84ce7c617d to your computer and use it in GitHub Desktop.
Save runspired/8780d2405d84ce7c617d to your computer and use it in GitHub Desktop.
/*
* Little example of how to use ```socket-io.client``` and ```request``` from node.js
* to authenticate thru http, and send the cookies during the socket.io handshake.
*/
var io = require('socket.io-client');
var request = require('request');
/*
* This is the jar (like a cookie container) we will use always
*/
var j = request.jar();
/*
* First I will patch the xmlhttprequest library that socket.io-client uses
* internally to simulate XMLHttpRequest in the browser world.
*/
var originalRequest = require('xmlhttprequest').XMLHttpRequest;
require('xmlhttprequest').XMLHttpRequest = function(){
originalRequest.apply(this, arguments);
this.setDisableHeaderCheck(true);
var stdOpen = this.open;
/*
* I will patch now open in order to set my cookie from the jar request.
*/
this.open = function() {
stdOpen.apply(this, arguments);
var header = j.get({ url: 'http://localhost:9000' })
.map(function (c) {
return c.name + "=" + c.value;
}).join("; ");
this.setRequestHeader('cookie', header);
};
};
/*
* Authenticate first, doing a post to some url
* with the credentials for instance
*/
request.post({
jar: j,
url: 'http://localhost:9000/login',
form: {username: 'jose', password: 'Pa123'}
}, function (err, resp, body){
/*
* now we can connect.. and socket.io will send the cookies!
*/
var socket = io.connect('http://localhost:9000');
socket.on('connect', function(){
console.log('connected! handshakedddddddddddd')
done();
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment