facing a CORS error - javascript

I'm facing a CORS error when I'm trying to download video from different domain. I tried a lot to solve it but couldn't.
Below is my js code.
getVideoFile = function () {
var xhr = new XMLHttpRequest(),
blob;
xhr.open("GET",myVideo, true);
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
blob = xhr.response;
putVideoInDb(blob);
window.alert("Video file downloaded");
}
else {
window.alert("Unable to download video");
}
}, false);
xhr.send();
};
putVideoInDb = function (blob) {
var transaction = db.transaction(["Videos"], "readwrite");
var store = transaction.objectStore("Videos");
var vid = {
videoName:videoName,
video:blob,
}
var request = store.add(vid);
request.onerror = function(e) {
console.log("Error",e.target.error.name);
}
request.onsuccess = function(e) {
console.log("Done!!");
}
};

xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
Set this header value before sending your request. For more information you can read here JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

Take a look at this question: CORS error on same domain?
Of course this is a scenario where the domain is the same, but however the logic's the same...
There's a lot of articles out there about this topic.

Related

Internet explorer throws TypeMismatchError at POST upload request with large body

I have few files (~30Mb every) that needs convert to base64 and upload for server. After uploading part of files IE11 throws TypeMismatchError. File content is a base64 string that it is not encoding problem. Panel of network requests do not contents it, request fails before sending. Another browsers are working without errors. How to fix it?
function post(url, data, timeout) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = (result) => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
resolve(xhr.responseText);
}
};
xhr.onerror = function (event) {
reject(event);
};
xhr.timeout = timeout;
xhr.send(data);
});
}
function handleFileSelect() {
post('/upload', LARGE_FILE_DATA_BASE64).catch(error => {
// Throws TypeMismatchError error after few uploads.
});
}
Google says about this similar problem only here: https://helperbyte.com/questions/276626/jquery-deferrer-typemismatcherror-when-you-bulk-load-data-cant-find-what-this-might-mean

Download mp3 file from url with xmlHttpRequest and writing it to file

I've currently tried every possible ways to do this but I cannot get it to work, despite reading every related question on the internet ...
I'm simply trying to download an mp3 arrayBuffer that i GET from an url with the module xmlHttpRequest from my node server code with the intent to then writing the buffer to an mp3 file, here is the code:
const endpoint = "https://cdns-preview-a.dzcdn.net/stream/c-ae4124ee0e63b9f6abffddb36b9695cf-2.mp3";
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var oReq = new XMLHttpRequest();
oReq.open("GET", endpoint, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
if (this.status != 200) {
console.log(this.status)
}
console.log(oReq.response);
var uInt8Array = new Uint8Array(oReq.response);
console.log(uInt8Array);
var dest = "1.mp3";
var stream = fs.createWriteStream(dest);
stream.write(uInt8Array);
stream.end();
}
};
oReq.send();
oReq.response is always empty, no matter what I type in oReq.responseType(arraybuffer, blob).
if I try to write oReq.responseText, it's always going to be some scuffed encoding because it was translated to text.
Can you give me advices, is there some underlying deep layer that I don't understand, is it possible to do what I wanna achieve?
Found a solution with http get instead of xmlHttpRequest:
const endpointe = "https://cdns-preview-a.dzcdn.net/stream/c-ae4124ee0e63b9f6abffddb36b9695cf-2.mp3";
https.get(endpointe, (res) => {
datatest = []
res.on('data', function(chunk) {
datatest.push(chunk);
console.log(chunk);
});
// The whole response has been received. Print out the result.
res.on('end', () => {
//console.log(data)
var dest = "test.mp3";
var stream = fs.createWriteStream(dest);
var buffer = Buffer.concat(datatest);
stream.write(buffer);
stream.end();
});
}).on('error', (e) => {
console.error(e);
});

Problem grabbing image from server with https request in PlayCanvas

I'm trying to use the PlayCanvas OAuth and CORS to request an image from a service via HTML request. as I understood the response return a JSON holding the data, and in this question I just want to save the path in the JSON to a .txt file located in the PlayCanvas Assets.
I'm not 100% sure about my code.
I haven't found how to grab the .txt into the JS script (it cannot be attached to an object)
will appreciate help with both
URL is
https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png
I've tried to use an async request like the example appearing here
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
in the 'createCORSRequest':
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
xhr.onload = function (e) {
if (xhr.readyState === 46) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
I tried to place the 'stringify' and 'download' commands in initialize (moved then inside the callback
and finally ended up with what's appearing here
var Https = pc.createScript('https');
var token = 'That's the PlayCanvas Token';
var request = 'curl -H "Authorization: Bearer '+token+'" ';
var ts_URL ='https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png';
// initialize code called once per entity
Https.prototype.initialize = function() {
var url = request+ts_URL;
// ref: curl -H "Authorization: Bearer nesgdxhiqe7hylfilr6ss1rds0gq1uj8" https://playcanvas.com/api/...
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
};
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
if(method=="GET")
{
loadFile(url, DownloadToText(xhr));
}
// else... all the other cases
return xhr;
}
function loadFile(url, callback /*, opt_arg1, opt_arg2, ... */) {
var xhr = new XMLHttpRequest();
xhr.callback = callback;
xhr.arguments = Array.prototype.slice.call(arguments, 2);
xhr.onload = xhrSuccess;
xhr.onerror = xhrError;
xhr.open("GET", url, true);
xhr.send(null);
}
function DownloadToText (ans)
{
JSON.stringify(ans);
download(ans, 'json.txt', 'text/plain');
}
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
function xhrSuccess() {
this.callback.apply(this, this.arguments);
}
function xhrError() {
console.error(this.statusText);
}
expected results: I expected a json.txt file to be downloaded with the URL of the image inside.
Actual results: when I launched the program and went to console, saw the image 1.png got a 404 Not Found error.
the json.txt was downloaded with '[object XMLHttpRequest]'.
Also
in the F12 i got that the link leading to the error is
https://launch.playcanvas.com/curl%20-H%20%22Authorization:%20Bearer%---theToken---%22%20https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png
while simply
https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png leads to the image.
but i can't get away from the prefix if i wanna pass through the OAuth.. which is why i don't understand what was i'm doing wrong.

How to set multiple headers data with XMLHttpRequest in async mode?

My api call requires me to pass the api key in the headers, but I'm getting error back from the api service {"error":"2424452","message":"Invalid Api Key"}
I know my api key is valid as I can make the same api call in Python just fine, example:
req = requests.Session()
req.headers.update({'x-api-key': 'my-api-key', 'X-Product': 'my-product-name'})
req.get(url)
But in javscript, the same call errors out. I believe I'm not setting the headers correctly or something?
var req = new XMLHttpRequest();
req.onreadystatechange=handleStateChange;
req.open("GET", "url", true);
req.setRequestHeader("Host", "api.domain.com", "x-api-key", "my-api-key", "X-Product", "my-product-name");
req.send();
This XMLHttpRequest is not a browser call, rather in an application that support XMLHttpRequest.
setRequestHeader sets one header and takes two arguments (the name and the value).
If you want to set multiple headers, then call setRequestHeader multiple times. Don't add extra arguments to the first call.
In case you don't want to set multiple headers explicitly you can use
function setHeaders(headers){
for(let key in headers){
xhr.setRequestHeader(key, headers[key])
}
}
setHeaders({"Host":"api.domain.com","X-Requested-With":"XMLHttpRequest","contentType":"application/json"})
downloadReportFile(id, query): Observable<Object[]> {
var url = `${environment.baseUrl}report?report_name=${id}${query}`;
return Observable.create(observer => {
let xhr = new XMLHttpRequest();
xhr.open('GET', `${url}`, true);
xhr.setRequestHeader(environment.AUTH_TOKEN_HEADER_KEY, 'Bearer '+
localStorage.getItem(environment.AUTH_TOKEN_STORE_KEY));
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let filename = "Claim_Report.csv"
var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var blob = new Blob([xhr.response], { type: "text/plain;charset=utf-8" });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
return;
}
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(blobURL);
}, 100);
} else {
observer.error(xhr.response);
}
}
}
xhr.send();
});
}

XDomainRequest (CORS) for XML causing "Access is denied" error in IE8 / IE9

Apologies if this appears to be a duplicate but I cannot see a clear answer to any of the similar questions.
When trying to do a CORS request for some XML I continually get an "Access is denied" JS error from IE8.
My code is adapted from this example:
// 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() {
// All HTML5 Rocks properties support CORS.
var url = 'http://updates.html5rocks.com';
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();
}
from http://www.html5rocks.com/en/tutorials/cors/
This should work in IE8 using XDomainRequest, and when I load the example page and click "Run sample" on the html5rocks page, it works in IE8. However, as soon as I copy the code to my own page and run, I get the "Access is denied" error on the xhr.open() line inside XDomainRequest.
This one has me really baffled - the server is definitely set up correctly so it's something to do with the frontend. Thanks in advance to anyone who can help!
OK, the problem was down to weirdnesses in IE8 & 9 which were solved with a few suggestions from this article: http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ (mainly setting some blank handler functions and wrapping the .send() in a 0 timeout).
Here's my final code which works in ie8/9/10/11 & FF/Chrome:
function doRequest(url) {
// Create the XHR object.
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open('get', url, true);
}else if(typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open('get', url);
}else{
// CORS not supported.
xhr = null;
};
if (!xhr) {
return;
};
// Response handlers.
xhr.onload = function() {
//do what you want with the response. Remember to use xhr.responseText for ie8 compatibility, because it doesn't have .responseXML
if(xhr.responseXML) {
xml = this.responseXML;
}else if(xhr.responseText){
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.loadXML(xhr.responseText);
};
};
xhr.onerror = function() {
//do what you want on error
};
//these blank handlers need to be set to fix ie9 http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/
xhr.onprogress = function () { };
xhr.ontimeout = function () { };
//do it, wrapped in timeout to fix ie9
setTimeout(function () {
xhr.send();
}, 0);
};

Categories

Resources