Reputation: 1194
I'm trying to make a cross-origin XMLHttpRequest
from within a web worker. The setup is as follows:
example.com
s3.amazon.com
Access-Control-Allow-Origin
headerThe code is as follows:
var xhr = new XMLHttpRequest();
//this will redirect to 'https://s3.amazon.com/...'
xhr.open('GET', 'https://example.com/document/1234/download');
xhr.send(null);
This code properly follows the redirect, both when called from the main JS file and from a web worker.
This code properly follows the redirect only when called from the main JS file. When called from a web worker, the request is aborted without an error or log message.
It's possible to make this work by editing the browser security settings and enabling "Access data sources across domains," but it is not viable to expect users to do so.
Upvotes: 8
Views: 1417
Reputation: 1194
There are several possible work-arounds to this problem, two of which I explored:
function callXHR() {
var xhr = new XMLHttpRequest();
//this will redirect to 'https://s3.amazon.com/...'
xhr.open('GET', 'https://example.com/document/1234/download');
xhr.send(null);
}
if(isIE) {
//callXHR in main js file
} else {
//callXHR in web worker
}
//from a web worker
if(isIE) {
//give the exact url so the xhr doesn't get a 302
callXHR('https://s3.amazon.com/...');
} else {
//this will follow the redirect to https://aws...
callXHR('https://example.com/document/1234/download');
}
I decided on Option 2 because I didn't want to give up the web worker.
The answers provided here were focused on CORS or redirects, but none actually addressed the specific problem I was having.
Upvotes: 1
Reputation: 655
Try setting up few more metatags in header request, like xhr.setRequestHeader('Access-Control-Allow-Origin', example.com ); // from which request is made
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// This is a sample server that supports CORS.
var url = 'https://example.com/document/1234/download';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
For more details check this link - https://www.html5rocks.com/en/tutorials/cors/
Upvotes: 0