【问题标题】:imgur api key not working from javascript?imgur api 密钥在 javascript 中不起作用?
【发布时间】:2013-06-05 23:33:00
【问题描述】:

我在 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,但是如果我使用在教程中找到的密钥,一切都会按预期工作。几天前我创建了密钥,所以我认为时间不是问题。还能是什么?

我认为问题在于有效的密钥是由 api 的 v2 生成的,而新的密钥是 v3,它不适用于指定的 v2。如果我指定 v3,我会得到“HTTP 访问被禁用。请求必须使用 ssl。”我怎样才能让它工作?

【问题讨论】:

  • 尝试执行 console.log(JSON.parse(xhr.responseText)) 以查看您的密钥的响应。您看到的错误是他们正在发送成功消息,但除了上传对象之外还有其他内容。
  • @AaronSaray 我在解析的 responseText 中得到“无效的 api 密钥”:/

标签: javascript jquery api imgur


【解决方案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);
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2015-07-28
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多