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.
Related
I want access html file in "https://www.setgame.com/set/puzzle" by JavaScript but I cannot.
I will show the JavaScript code what I make and the error log.
// 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(url) {
// This is a sample server that supports CORS.
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
alert(xhr.status)
var text = xhr.responseText;
alert(text)
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert(xhr.responseText)
alert('Woops, there was an error making the request.');
};
xhr.send();
}
makeCorsRequest("https://www.setgame.com/set/puzzle")
Chrome shows the following errors.
Failed to load resource: the server responded with a status of 404 (Not Found)
Access to XMLHttpRequest at 'https://www.setgame.com/set/puzzle' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If you want to send CORS request successfully, origin server (in this case, setgame.com) must allow CORS request. (With Access-Control-Allow-Origin header)
This means, you can't access CORS-blocked server by browser-side javascript.
Try use node.js (server-sided things)
This is the url that I'm trying to get the JSON from: https://shopicruit.myshopify.com/admin/orders.json?page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6
However, I have tried both CORS but it failed. Here is my code following from a template:
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() {
var url = 'https://shopicruit.myshopify.com/admin/orders.json?page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function () {
var text = xhr.responseText;
console.log("success");
};
xhr.onerror = function () {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
makeCorsRequest();
It still gives me this error:
XMLHttpRequest cannot load >https://shopicruit.myshopify.com/admin/orders.json?>page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6. No 'Access-Control->Allow-Origin' header is present on the requested resource. Origin 'null' >is therefore not allowed access.
I also tried JSONP but it looks like it doesn't support JSONP.
Any help and insights will be appreciated!
Issue occurs because XMLHTTPRequest causes CORS issues. XMLHTTPRequest call should be made to same domain from browser.
https://shopicruit.myshopify.com has to implement Access-Control-Allow-Origin : * header in the response in order to access from all domains.
Else you can use your server as a proxy.
How do I use CORS for data retrieval from a HTTPS URL to localhost in JavaScript? The URL is a Service-Now incident list that I need to process as a JSON object.
Here is how you do it, provided server side configurations are done:
// 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();
}
This is from: http://www.html5rocks.com/en/tutorials/cors/
CORS is a server side feature that the new browsers support.
When you request a resource from a cross domain service, the browser performs a preflight request to the server and asks him for access information.
If the server allows you to access it's resource from a different domain, it will send back some HTTP headers and the browser will decide upon those headers about your actions.
Read more here.
I am posting some data to server through Backbone.js and server sends a csv file as response. As Backbone.js handles only json format can some body tell me how to handle this case, so that i would be able to download the csv file gracefully.
object = {};
object.c1 = formObj.c1
hash = {
success: function(model, response, options) {
},
error: function(model, response, options) {
return console.log(response);
}
};
model = new P.models.mine(object);
model.doSomething(object, hash);
It always comes to error part.
The ideal way to handle this would be to change your back end code to return JSON, or create another route that returns JSON. Since you are asking this question I'm assuming that isn't an option for you.
Basically you are going to have to parse the CSV on the client side:
https://stackoverflow.com/a/1293163/944006 - Should get you started.
If you are asking to download a csv file, then just pointing the browser at the location should prompt the user for download. You cannot prompt a file download through ajax(for good reason), but there are ways to tiptoe around this limitation:
https://stackoverflow.com/a/9970672/944006
You could also use plain javascript rather than Backbone.js. Believe me this is the best way.
Here is some code:
var xhr = new XMLHttpRequest();
xhr.open('POST', Urls.download, true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Authorization", "Bearer " + access_token);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function (e) {
if (this.status == 200) {
var blob = new Blob([this.response], { type: 'application/vnd.ms-excel' });
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.id = "a" + new Date().getTime();
a.setAttribute("data-bypass", "");
a.href = downloadUrl;
a.download = "list_" + new Date().getTime() + ".xlsx";
document.body.appendChild(a);
a.click();
} else {
alert('Unable to download excel.')
}
};
xhr.send(JSON.stringify(this.obj));
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);
};