Angularjs 无法加载XMLHttpRequesthttp://localhost:57997/Home/Get
当我试图从MVC访问WebApi时,我得到了这个错误Angularjs 无法加载XMLHttpRequesthttp://localhost:57997/Home/Get,angularjs,asp.net-mvc-4,asp.net-web-api,Angularjs,Asp.net Mvc 4,Asp.net Web Api,当我试图从MVC访问WebApi时,我得到了这个错误 XMLHttpRequest cannot load http://localhost:57997/Home/Get. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64035' is therefore not allowed acces Service.Js app.servic
XMLHttpRequest cannot load http://localhost:57997/Home/Get. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64035' is therefore not allowed acces
Service.Js
app.service('MyService', function ($http) {
var ApiAddress = "http://localhost:57997/";
this.GetWebData = function () {
var Getdatas= $http({
url: ApiAddress + 'Home/Get',
type: 'GET',
dataType: 'json',
params: JSON.stringify(),
content:{'content-type' :'application/Json'}
})
return Getdatas;
}
});
app.controller('WebCtrls', function ($scope,MyService) {
$scope.Hello = "Hello angular How r u...";
$scope.GetDb = function () {
alert('Hello..');
var SerData = MyService.GetWebData();
SerData.then(function (d) {
$scope.Emp = d.data;
})
}
})
Controller.Js
app.service('MyService', function ($http) {
var ApiAddress = "http://localhost:57997/";
this.GetWebData = function () {
var Getdatas= $http({
url: ApiAddress + 'Home/Get',
type: 'GET',
dataType: 'json',
params: JSON.stringify(),
content:{'content-type' :'application/Json'}
})
return Getdatas;
}
});
app.controller('WebCtrls', function ($scope,MyService) {
$scope.Hello = "Hello angular How r u...";
$scope.GetDb = function () {
alert('Hello..');
var SerData = MyService.GetWebData();
SerData.then(function (d) {
$scope.Emp = d.data;
})
}
})
WebApi
public JsonResult Get()
{
var x = prod.GetEmployees();
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Global.asax
在WebApi全局文件中,我为跨页面源代码编写了以下代码
protected void Application_BeginRequest()
{
string[] allowedOrigin = new string[] { "http://localhost:57997/" };
var origin = HttpContext.Current.Request.Headers["Origin"];
if (origin != null && allowedOrigin.Contains(origin))
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
//Need to add more later , will see when required
}
}
您可以通过从chrome.exe所在的文件夹位置执行以下命令来禁用chrome浏览器的web安全选项来处理此问题。首先关闭所有chrome实例。然后运行以下命令 chrome.exe--禁用web安全 您可以在服务器端处理它,同时过滤所有发送到服务器的请求,将头添加到响应中,如下所示
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
错误消息清楚地表明原点为
http://localhost:64035
。资源位于http://localhost:57997/
。端口64035正在尝试对端口57997进行跨源访问。另外,OPTIONS
应该是一个允许的方法。所以如何克服这个问题呢?您的这行“string[]allowedOrigin=newstring[]{”“};”应该像这个string[]allowedOrigin=newstring[]{”“};