我已经使用Web API 2和MCV 5开发了Web应用程序。 我尝试使用javascript调用Web api并获取NetworkError:无法在'XMLHttpRequest'上执行'send':无法将'Sub.domain.com'加载到控制台。
var param = {
"EmailID": email,
};
var appUrl = '@ConfigHelper.ApiURL';
var url = appUrl + 'user/checkemailid';
//create xml http request for request api url
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(param),
contentType: "application/json",
dataType: "json",
success: function (json) {
debugger;
if (json.IsSuccessful) {
swal("", "Email id already exist.", "warning");
return false;
}
else {
return true;
}
},
error: function (data) {
debugger;
swal('', data.Message, 'error');
}
});
,还为项目Web和api添加交叉原点。 将以下代码写入web.config
<system.webServer>
<!-- Cross origin for Domain-->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
并将代码添加到global.aspx文件
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
让我知道我在哪里缺少任何东西。
我正在尝试实施许多解决方案,例如 Failed to execute 'send' on 'XMLHttpRequest' Syncronous,但不走运
该代码段适用于其他域的该项目,但不适用于从主域到子域的api调用。
答案 0 :(得分:0)
您也可以在$ .ajax()参数对象中添加以下内容-
"crossDomain": true,
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}