Ключ API imgur не работает из javascript?

Я зарегистрировал приложение на imgur.com (для анонимного использования) и получил ключ приложения. Я использую его здесь:

self.uploadImage = function(file) {

        /* Is the file an image? */
        if (!file || !file.type.match(/image.*/)) return;

        /* It is! */
        document.body.className = "uploading";

        /* Lets build a FormData object*/
        var fd = new FormData(); // I wrote about it: https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
        fd.append("image", file); // Append the file
        fd.append("key", "<my key>"); // Get your own key http://api.imgur.com/
        var xhr = new XMLHttpRequest(); // Create the XHR (Cross-Domain XHR FTW!!!) Thank you sooooo much imgur.com
        xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
        xhr.onload = function() {
            // reference side-specific class here
            document.querySelector("#image-uploaded-one-" + self.cardId()).href = JSON.parse(xhr.responseText).upload.links.imgur_page;

        }
        // Ok, I don't handle the errors. An exercice for the reader.

        /* And now, we send the formdata */
        xhr.send(fd);
    };

Если я использую свой ключ, я получаю сообщение об ошибке Cannot read property 'links' of undefined, однако, если я использую тот, который я нашел в учебнике, все работает так, как ожидалось. Я создал ключ несколько дней назад, поэтому не думаю, что проблема во времени. Что еще это может быть?

Я думаю, проблема в том, что ключ, который работает, был сгенерирован v2 API, а новые - v3, которые не будут работать с указанным v2. Если я укажу v3, я получаю «HTTP-доступ отключен. Запросы должны использовать ssl». Как я могу заставить это работать?


person SB2055    schedule 05.06.2013    source источник
comment
Попробуйте выполнить console.log(JSON.parse(xhr.responseText)) чтобы увидеть, что ответит на ваш ключ. Ошибка, которую вы видите, заключается в том, что они отправляют сообщение об успешном завершении, но с чем-то еще, кроме объекта загрузки.   -  person Aaron Saray    schedule 06.06.2013
comment
@AaronSaray Я получаю неверный ключ API в проанализированном responseText:/   -  person SB2055    schedule 06.06.2013


Ответы (1)


Следующий код исправил это:

self.uploadImage = функция (файл) {

        /* Is the file an image? */
        if (!file || !file.type.match(/image.*/)) return;

        /* It is! */
        document.body.className = "uploading";

        /* Lets build a FormData object*/
        var fd = new FormData(); // I wrote about it: https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
        fd.append("image", file); // Append the file
        var xhr = new XMLHttpRequest(); // Create the XHR (Cross-Domain XHR FTW!!!) Thank you sooooo much imgur.com
        xhr.open("POST", "https://api.imgur.com/3/image.json"); // Boooom!
        xhr.onload = function () {
            var response1 = JSON.parse(xhr.responseText);
            var response = JSON.parse(xhr.responseText).data.link;
            document.querySelector("#image-uploaded-one-" + self.cardId()).href = response;

        }
        // Ok, I don't handle the errors. An exercice for the reader.
        xhr.setRequestHeader('Authorization', 'Client-ID <yourkey>');

        /* And now, we send the formdata */
        xhr.send(fd);
    };
person SB2055    schedule 06.06.2013