【发布时间】:2018-11-29 19:36:39
【问题描述】:
其实,我想从这个 url 得到一个 JSON 对象,
我尝试在 javascript 中使用XMLHttpRequest(),但控制台记录了此错误:[CORS] The origin 'http://localhost' did not find 'http://localhost' in the Access-Control-Allow-Origin response header for cross-origin resource at 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN'.
但是当我在浏览器地址栏中输入 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>
注意:我无法控制服务器。
【问题讨论】:
-
当你直接在浏览器中访问时,不再是跨域请求,因为你是直接访问bing。除非您能以某种方式实现服务器端代码来运行请求,否则从前端代码运行跨域请求的唯一方法是手动禁用浏览器安全设置。
标签: javascript html json cross-domain