From 41f4bf5f3dd274c93738938b35eaf2c0a5428ea9 Mon Sep 17 00:00:00 2001 From: Austin Pray Date: Tue, 31 Oct 2017 14:51:38 -0700 Subject: [PATCH] Prefer fetch API over XHR closes https://github.com/getsentry/raven-js/issues/930 --- src/raven.js | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/src/raven.js b/src/raven.js index 1d2e9008fc14..fcecb31514a6 100644 --- a/src/raven.js +++ b/src/raven.js @@ -1881,7 +1881,36 @@ Raven.prototype = { }); }, + /** + * @param {string} opts.url + * @param {Object} opts.auth + * @param {*} opts.data + * @param {Object} opts.options + * @callback opts.onSuccess + * @callback opts.onError + * @private + */ _makeRequest: function(opts) { + // NOTE: auth is intentionally sent as part of query string (NOT as custom + // HTTP header) so as to avoid preflight CORS requests + var url = opts.url + '?' + urlencode(opts.auth); + + // https://github.com/Modernizr/Modernizr/blob/d5f881a4de0d5fc1af85921ce9c7dc3919c6d335/feature-detects/network/fetch.js + if ('fetch' in _window) { + return _window.fetch(url, { + method: 'POST', + body: stringify(opts.data) + }).then(function (response) { + if (!response.ok) { + return opts.onError && opts.onError(new Error('Sentry error code: ' + response.status)) + } + + opts.onSuccess && opts.onSuccess(); + })["catch"](function () { + opts.onError && opts.onError(new Error('Sentry error code: network unavailable')); + }) + } + var request = _window.XMLHttpRequest && new _window.XMLHttpRequest(); if (!request) return; @@ -1890,8 +1919,6 @@ Raven.prototype = { if (!hasCORS) return; - var url = opts.url; - if ('withCredentials' in request) { request.onreadystatechange = function() { if (request.readyState !== 4) { @@ -1923,9 +1950,7 @@ Raven.prototype = { } } - // NOTE: auth is intentionally sent as part of query string (NOT as custom - // HTTP header) so as to avoid preflight CORS requests - request.open('POST', url + '?' + urlencode(opts.auth)); + request.open('POST', url); request.send(stringify(opts.data)); },