Ru1*_*u11 69 ajax cross-domain cors angularjs
XMLHttpRequest cannot load http://mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
当我尝试从我的代码中运行我的Web服务时,我收到此错误.我试着找到它并尝试了许多我在网上找到的解决方案.粘贴下面的代码.
<form name="LoginForm" ng-controller="LoginCtrl" ng-submit="init(username,password,country)">
<label>Country</label><input type="text" ng-model="country"/><br/><br/>
<label>UserName</label><input type="text" ng-model="username" /></br></br>
<label>Password</label><input type="password" ng-model="password">
</br>
<button type="submit" >Login</button>
</form>
Run Code Online (Sandbox Code Playgroud)
而控制器形成相应的js是:
app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
$scope.login = function (credentials) {
$http.get('http://mywebservice').success(function ( data ) {
alert(data);
});
}
}]);
Run Code Online (Sandbox Code Playgroud)
当我从URL栏点击它时,网络服务工作正常.如何解决问题?请帮忙!
Pat*_*ova 26
在Chrome网上应用店有一个扩展,增加了"访问控制允许来源"标头为你的时候是在试图访问一个不同的主机比你的页面的异步调用.
扩展名为:" Allow-Control-Allow-Origin:* ",这是以下链接:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
小智 18
在客户端,您可以通过AngularJS启用cors请求
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
Run Code Online (Sandbox Code Playgroud)
但是,如果仍然返回错误,则表示您发出请求的服务器必须允许CORS请求,并且必须为此配置.
小智 16
这是一个CORS问题.有一些设置可以改变角度 - 这些是我通常在Angular .config方法中设置的(并非所有都与CORS相关):
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
Run Code Online (Sandbox Code Playgroud)
您还需要配置Web服务 - 具体细节取决于您使用的服务器端语言.如果您使用网络监控工具,您会看到它最初发送OPTIONS请求.您的服务器需要适当响应以允许CORS请求.
它在你的浏览器中工作的原因是因为它不是一个跨源请求 - 而你的Angular代码是.
归档时间: |
|
查看次数: |
163906 次 |
最近记录: |