diff --git a/src/RESTController.js b/src/RESTController.js index 4e0653239..520358ff2 100644 --- a/src/RESTController.js +++ b/src/RESTController.js @@ -169,24 +169,24 @@ const RESTController = { headers[key] = customHeaders[key]; } - function handleProgress(type, event) { - if (options && typeof options.progress === 'function') { + if (options && typeof options.progress === 'function') { + const handleProgress = function (type, event) { if (event.lengthComputable) { options.progress(event.loaded / event.total, event.loaded, event.total, { type }); } else { options.progress(null, null, null, { type }); } - } - } - - xhr.onprogress = event => { - handleProgress('download', event); - }; + }; - if (xhr.upload) { - xhr.upload.onprogress = event => { - handleProgress('upload', event); + xhr.onprogress = event => { + handleProgress('download', event); }; + + if (xhr.upload) { + xhr.upload.onprogress = event => { + handleProgress('upload', event); + }; + } } xhr.open(method, url, true); diff --git a/src/__tests__/RESTController-test.js b/src/__tests__/RESTController-test.js index f2074c47a..85524d85c 100644 --- a/src/__tests__/RESTController-test.js +++ b/src/__tests__/RESTController-test.js @@ -570,6 +570,20 @@ describe('RESTController', () => { ); }); + it('does not set upload progress listener when callback is not provided to avoid CORS pre-flight', () => { + const xhr = { + setRequestHeader: jest.fn(), + open: jest.fn(), + upload: jest.fn(), + send: jest.fn(), + }; + RESTController._setXHR(function () { + return xhr; + }); + RESTController.ajax('POST', 'users', {}); + expect(xhr.upload.onprogress).toBeUndefined(); + }); + it('does not upload progress when total is uncomputable', done => { const xhr = mockXHR([{ status: 200, response: { success: true } }], { progress: { diff --git a/src/__tests__/test_helpers/mockXHR.js b/src/__tests__/test_helpers/mockXHR.js index 866ead408..80d931cb8 100644 --- a/src/__tests__/test_helpers/mockXHR.js +++ b/src/__tests__/test_helpers/mockXHR.js @@ -35,8 +35,14 @@ function mockXHR(results, options = {}) { this.readyState = 4; attempts++; this.onreadystatechange(); - this.onprogress(options.progress); - this.upload.onprogress(options.progress); + + if (typeof this.onprogress === 'function') { + this.onprogress(options.progress); + } + + if (typeof this.upload.onprogress === 'function') { + this.upload.onprogress(options.progress); + } }, }; return XHR;