我有一个 ASP.NET WebForms项目。在按钮单击事件中,我调用JavaScript方法来执行XMLHttpRequest,以获取JSON格式的所有国家/地区名称。我有一个访问控制允许来源错误。我该如何解决?
var url = "http://country.io/names.json";
function meth1() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
console.log("ready " + this.readyState + " status " + this.status);
console.log(this.response);
}
}
xmlhttp.open("get", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send();
}
<form id="form1" runat="server">
<div>
<h4>Test xmlhttprequest on cors</h4>
<input type="button" value="Get ajax cors" onclick="meth1()" />
</div>
</form>
这是我在服务器端设置的代码:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:53410/");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
}
您正在向未设置Access-Control-Allow-Origin
标头(http://country.io/names.json(的网站发出请求。如果对此 URL 执行OPTIONS
请求,将得到以下结果:
<h1>403 Forbidden</h1>
<ul>
<li>Code: AccessForbidden</li>
<li>Message: CORSResponse: CORS is not enabled for this bucket.</li>
<li>Method: GET</li>
<li>ResourceType: BUCKET</li>
</ul>
这意味着,如果您对本网站进行XMLHttpRequest
,您的浏览器将自动阻止响应。
您可以下载并保存 JSON 文件并将其存储在本地服务器上,以便您可以通过 XMLHttpRequest
访问它。
例如:
var url = "http://localhost:<portnumber>/names.json";
function meth1() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
console.log("ready " + this.readyState + " status " + this.status);
console.log(this.response);
}
}
xmlhttp.open("get", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send();
}