-
-
Save danielmontenegro/144f36e90a70db14b8cf2fb49c52b8a1 to your computer and use it in GitHub Desktop.
socket-io.client send the cookies!
This file contains hidden or 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
/* | |
* 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