Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to send custom http headers to server #21

Merged
merged 1 commit into from
Apr 19, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion lib/eventsource.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@ var http = require('http')
, events = require('events')
, eventstream = require('./eventstream');

function isPlainObject(obj) {
return Object.getPrototypeOf(obj) === Object.prototype;
}

/**
* Creates a new EventSource object
*
* @param {String} url the URL to which to connect
* @param {Object} headers headers to use
* @api public
**/
function EventSource(url) {
function EventSource(url, headers) {
var readyState = EventSource.CONNECTING;
Object.defineProperty(this, 'readyState', {
get: function() {
Expand Down Expand Up @@ -54,6 +59,12 @@ function EventSource(url) {
var isSecure = options.protocol == 'https:';
options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' };
if (lastEventId) options.headers['last-event-id'] = lastEventId;
if (headers && isPlainObject(headers)) {
for (var i in headers) {
var header = headers[i];
options.headers[i] = header;
}
}

req = (isSecure ? https : http).request(options, function(res) {
// Handle HTTP redirects
Expand Down
23 changes: 23 additions & 0 deletions test/eventsource_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,29 @@ exports['HTTP Request'] = {
}, function(req) { headers = req.headers; });
},

'sets headers by user': function(test) {
var url = 'http://localhost:' + port;
var headers = {
'User-Agent': 'test',
'Cookie': 'test=test'
};
createServer([],
function(close) {
var es = new EventSource(url, headers);
es.onopen = function() {
es.close();
close(test.done);
};
},
function(req, res) {
test.equal(req.headers['user-agent'], headers['User-Agent']);
test.equal(req.headers['cookie'], headers['Cookie']);
res.writeHead(200);
res.end();
return true;
});
},

'follows http 301 redirect': function(test) {
var headers;
var url = 'http://localhost:' + port;
Expand Down