【问题标题】:Fetch CORS error with instagram api使用 instagram api 获取 CORS 错误
【发布时间】:2018-01-12 12:17:26
【问题描述】:

我正在尝试从 instagram api 获取一些数据,但我不断收到以下错误: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.instagram.com/v1/users/1652250683/media/recent/?MYTOKEN&count=20&callback=?. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
我还检查了 instagram 开发网站上的所有内容,所有选项似乎都很好。 这是我的代码:

fetch('https://api.instagram.com/v1/users/1652250683/media/recent/?MYTOKEN&count=20&callback=', {
    mode: 'cors'
})
    .then(response => response.json())
    .then(function(data) {

        const response = data;

        const images = response['data'].map(img => {
            return [img.images.standard_resolution.url]
        })

        const topImgs = images.slice(0, 7);
        const leftImgs = images.slice(7, 10);
        const rightImgs = images.slice(10, 13);
        const bottomImgs = images.slice(13, 20);

        let topDivs = document.querySelector('.top').children;
        let leftDivs = document.querySelector('.left').children;
        let rightDivs = document.querySelector('.right').children;
        let bottomDivs = document.querySelector('.bottom').children;

        function* enumerate(iterable) {
            let i = 0;

            for (const x of iterable) {
                yield [i, x];
                i++;
            }
        }

        for (const [i, div] of enumerate(topDivs)) {
            div.innerHTML = `<img src="${topImgs[i]}">`
        }

        for (const [i, div] of enumerate(leftDivs)) {
            div.innerHTML = `<img src="${leftImgs[i]}">`
        }

        for (const [i, div] of enumerate(rightDivs)) {
            div.innerHTML = `<img src="${rightImgs[i]}">`
        }
        for (const [i, div] of enumerate(bottomDivs)) {
            div.innerHTML = `<img src="${bottomImgs[i]}">`
        }       

    })
    .catch(function(error) {
        // If there is any error you will catch them here
        console.log(error);
    });

如您所见,我只想获得非常简单的图像。在本地,我正在使用适用于 chrome 的 CORS 插件,它工作正常,但在服务器上却不行。有谁知道可能是什么问题以及如何解决它?

【问题讨论】:

  • &amp;callback=? ... 建议您期待 JSONP - 就此而言,您不会使用 fetch 或 XMLHttpRequest 获得 JSONP ...您使用具有 src 属性的脚本标记(或 JQuery,如果必须)
  • 我刚刚添加了“?”作为最后一次尝试,看看它是否可以这样工作。原始代码只有“&callback=”,我将编辑帖子以强调这一点
  • 不是吗?是 callback= 表明它是 JSONP 类型的 API。这意味着您不能像我说的那样使用 fetch 或 xmlhttprequest 。您需要阅读 JSONP 的工作原理
  • 在您的服务器上使用代理以避免暴露您的凭据
  • @JaromandaX 所以基本上我应该尝试用 JQ 来做?此外,我认为我可以通过在 instagram 上的开发人员选项卡中启用有效 url 来实现它。

标签: javascript ajax fetch


【解决方案1】:

所以,为了解决这个问题,你们有几种可能性。其中之一是使用支持 JSONP 的 JQ。
您的代码将如下所示:

var token = 'your token',
    numPhotos = 20

$.ajax({
    url: 'https://api.instagram.com/v1/users/self/media/recent/',
    dataType: 'jsonp',
    type: 'GET',
    data: {access_token: token, count: numPhotos},
    success: function(data){
        console.log(data);
        // Do something
    },
    error: function(data){
        console.log(data);
    }
});

您可以阅读here 详细了解 Instagram 对照片数量的限制。

还有使用纯 JS 获取数据的方法。
来自他们的文档:If you're writing an AJAX application, and you'd like to wrap our response with a callback, all you have to do is specify a callback parameter with any API call.

考虑到这一点,您可以执行以下操作:

var token = 'your token',
    numPhotos = 20,
    scrElement = document.createElement( 'script' );

window.instaFunction = function( data ) {
    console.log(data);
    // Do something
}

scrElement.setAttribute( 'src', 'https://api.instagram.com/v1/users/self/media/recent?access_token=' + token + '&count=' + numPhotos + '&callback=instaFunction' );
document.body.appendChild( scrElement );

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 2017-02-02
    • 2019-01-23
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多