其实我想从这个url获取一个JSON对象,
我尝试在 javascript 中使用 XMLHttpRequest()
但控制台记录了此错误: [CORS] The origin 'http://localhost' did not find 'http://localhost' in the Access- “http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN”处的跨源资源的 Control-Allow-Origin 响应 header 。
但是当我在浏览器地址栏中输入 url 时,它加载正确!看截图!
查看我的 JavaScript 代码:
<script>
var url='http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN';
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
getJSON('http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN',
function(err, data) {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
console.log(data);
}
});
</script>
注意:我无法控制服务器。
最佳答案
您可以在此处查看有关 CORS
的信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
对于您的问题,您可以通过https://cors.io
等服务代理您的请求来解决。例如,在控制台中运行以下命令:
fetch('https://cors.io?http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN')
.then(res => res.json())
.then(data => console.log(data))
请记住,这不是理想的解决方案,因为在这种情况下您的代码将依赖于第三方服务。这对于一些个人家庭项目来说是可以的,但对于大型公司项目来说就不行了。
关于javascript - [CORS] :' Access-Control-Allow-Origin' 不允许获取跨域 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50952116/