我正在尝试使用PlayCanvas OAuth和CORS通过HTML请求从服务中请求图像。据我所知,响应返回一个保存数据的JSON,在这个问题中,我只想将JSON中的路径保存到位于PlayCanvas资产中的.txt文件中。
我不确定我的代码是否100%。 我还没有找到如何将.txt捕获到JS脚本中的方法(无法将其附加到对象上)
将很高兴为您提供帮助
URL是 https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png
我尝试使用异步请求,例如此处显示的示例 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests 在“ 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);
};
我试图将'stringify'和'download'命令放在initialize中(先移到回调中,然后移入
最后是这里出现的内容
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);
}
预期结果:我希望下载一个带有图像URL的json.txt文件。
实际结果:当我启动程序并进入控制台时,看到图像1.png出现404 Not Found错误。
json.txt是通过“ [object XMLHttpRequest]”下载的。
也 在F12中,我知道导致错误的链接是 https://launch.playcanvas.com/curl%20-H%20%22Authorization:%20Bearer%---theToken---%22%20https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png
同时 https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png引出图片。
但是如果我想通过OAuth,就无法摆脱前缀。这就是为什么我不明白自己在做什么错。