diff --git a/src/EventSource.js b/src/EventSource.js index 6a7b146..cbc46b5 100644 --- a/src/EventSource.js +++ b/src/EventSource.js @@ -31,12 +31,22 @@ class EventSource { this.timeout = options.timeout ?? 0; this.timeoutBeforeConnection = options.timeoutBeforeConnection ?? 500; this.withCredentials = options.withCredentials || false; - this.headers = options.headers || {}; this.body = options.body || undefined; this.debug = options.debug || false; this.interval = options.pollingInterval ?? 5000; this.lineEndingCharacter = options.lineEndingCharacter || null; + const defaultHeaders = { + Accept: 'text/event-stream', + 'Cache-Control': 'no-cache', + 'X-Requested-With': 'XMLHttpRequest', + }; + + this.headers = { + ...defaultHeaders, + ...options.headers + }; + this._xhr = null; this._pollTimer = null; this._lastIndexProcessed = 0; @@ -76,14 +86,8 @@ class EventSource { this._xhr.withCredentials = true; } - this._xhr.setRequestHeader('Accept', 'text/event-stream'); - this._xhr.setRequestHeader('Cache-Control', 'no-cache'); - this._xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); - - if (this.headers) { - for (const [key, value] of Object.entries(this.headers)) { - this._xhr.setRequestHeader(key, value); - } + for (const [key, value] of Object.entries(this.headers)) { + if(value) this._xhr.setRequestHeader(key, value); } if (this.lastEventId !== null) { @@ -196,6 +200,7 @@ class EventSource { } const parts = response.substring(this._lastIndexProcessed, indexOfDoubleNewline).split(this.lineEndingCharacter); + this._lastIndexProcessed = indexOfDoubleNewline; let type = undefined;