【发布时间】: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 插件,它工作正常,但在服务器上却不行。有谁知道可能是什么问题以及如何解决它?
【问题讨论】:
-
&callback=?... 建议您期待 JSONP - 就此而言,您不会使用 fetch 或 XMLHttpRequest 获得 JSONP ...您使用具有 src 属性的脚本标记(或 JQuery,如果必须) -
我刚刚添加了“?”作为最后一次尝试,看看它是否可以这样工作。原始代码只有“&callback=”,我将编辑帖子以强调这一点
-
不是吗?是 callback= 表明它是 JSONP 类型的 API。这意味着您不能像我说的那样使用 fetch 或 xmlhttprequest 。您需要阅读 JSONP 的工作原理
-
在您的服务器上使用代理以避免暴露您的凭据
-
@JaromandaX 所以基本上我应该尝试用 JQ 来做?此外,我认为我可以通过在 instagram 上的开发人员选项卡中启用有效 url 来实现它。
标签: javascript ajax fetch