Проблема с захватом изображения с сервера с помощью https запроса в PlayCanvas - PullRequest
0 голосов
/ 14 февраля 2019

Я пытаюсь использовать PlayCanvas OAuth и CORS для запроса изображения из сервиса через HTML-запрос.как я понял, ответ возвращает JSON, содержащий данные, и в этом вопросе я просто хочу сохранить путь в файле JSON в файл .txt, расположенный в активах PlayCanvas.

Я не уверен на 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); 
}

ожидаемые результаты: я ожидал загрузки файла json.txt с URL-адресом изображения внутри.

Фактические результаты: когда я запустил программу и пошел в консоль, увидел изображение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 ... вот почему я не понимаю, что я делаюнеправильно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...