我尝试从服务器获取 json 以进行进一步操作并得到错误。
Access to XMLHttpRequest at 'http://www.mrsoft.by/data.json' from origin 'http://localhost:1234' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我在谷歌上搜索到这是标题的问题,尝试以不同的方式传递它们,但没有成功。
var requestURL = 'http://www.mrsoft.by/data.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var obj = request.response;
console.log(obj);
}
浏览器禁止向另一个域发出 XHR 请求。
一种选择是让服务器在请求此文件时返回标头。
Access-Control-Allow-Origin
例如
另一种选择是使用代理。有像这样的公共代理https://jsonp.afeld.me/
或者,如果可能的话,编写一个可以在您的域(本地主机)上使用的简单代理,那么浏览器就不会发誓。