요청 된 리소스에 'Access-Control-Allow-Origin'헤더가 없습니다. 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.
내 코드 내에서 웹 서비스를 실행하려고하면이 오류가 발생합니다. 나는 그것에 대해 찾아 보았고 그물에서 찾은 많은 솔루션을 시도했습니다. 아래 코드를 붙여 넣습니다.
<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>
그리고 해당 js를 구성하는 컨트롤러는 다음과 같습니다.
app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
$scope.login = function (credentials) {
$http.get('http://mywebservice').success(function ( data ) {
alert(data);
});
}
}]);
웹 서비스는 URL 표시 줄에서 클릭하면 제대로 작동합니다. 문제를 해결하는 방법? 친절하게 도와주세요!
크롬 웹 스토어는 '액세스 - 제어 - 허용 - 원산지'당신을위한 헤더를 시도가 당신보다 다른 호스트에 액세스 할 수있는 페이지의 비동기 호출이있을 때 추가하는 확장자를 갖습니다.
확장 프로그램의 이름은 " Allow-Control-Allow-Origin : * "이며 링크 : https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
클라이언트 측에서는 다음을 통해 AngularJS에서 cors 요청을 활성화 할 수 있습니다.
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
그러나 이것이 여전히 오류를 반환하는 경우 이는 요청하는 서버가 CORS 요청을 허용해야하며이를 위해 구성되어야 함을 의미합니다.
이것은 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";
또한 웹 서비스를 구성해야합니다. 자세한 내용은 사용중인 서버 측 언어에 따라 다릅니다. 네트워크 모니터링 도구를 사용하는 경우 처음에 OPTIONS 요청을 보내는 것을 볼 수 있습니다. CORS 요청을 허용하려면 서버가 적절하게 응답해야합니다.
브라우저에서 작동하는 이유는 교차 출처 요청을하지 않기 때문입니다. 반면 Angular 코드는 그렇습니다.
아래에 해결책이 있으며 그 효과가 있습니다.
app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
$scope.login = function (credentials) {
$http({
method: 'jsonp',
url: 'http://mywebservice',
params: {
format: 'jsonp',
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
alert(response.data);
});
}
}]);
' http : // mywebservice '에는 데이터와 함께 JSON_CALLBACK 을 반환 하는 콜백 매개 변수 가 필요합니다 . 아래에 완벽하게 작동하는 샘플 예가 있습니다.
$scope.url = "https://angularjs.org/greet.php";
$http({
method: 'jsonp',
url: $scope.url,
params: {
format: 'jsonp',
name: 'Super Hero',
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
alert(response.data);
});
예제 출력 :
{"name":"Super Hero","salutation":"Apa khabar","greeting":"Apa khabar Super Hero!"}
나는 이것을 추가했고 그것은 나를 위해 잘 작동했습니다.
web.api
config.EnableCors();
그런 다음 cors를 사용하여 모델을 호출합니다.
In a controller you will add at the top for global scope or on each class. It's up to you.
[EnableCorsAttribute("http://localhost:51003/", "*", "*")]
Also, when your pushing this data to Angular it wants to see the .cshtml file being called as well, or it will push the data but not populate your view.
(function () {
"use strict";
angular.module('common.services',
['ngResource'])
.constant('appSettings',
{
serverPath: "http://localhost:51003/About"
});
}());
//Replace URL with the appropriate path from production server.
I hope this helps anyone out, it took me a while to understand Entity Framework, and why CORS is so useful.
In my case, I was trying to hit a WebAPI service on localhost from inside an MVC app that used a lot of Angular code. My WebAPI service worked fine with Fiddler via http://localhost/myservice. Once I took a moment to configure the MVC app to use IIS instead of IIS Express (a part of Visual Studio), it worked fine, without adding any CORS-related configuration to either area.
I got
No 'Access-Control-Allow-Origin' header is present
and the problem was with the URL I was providing. I was providing the URL without a route, e.g., https://misty-valley-1234.herokuapp.com/
.
When I added a path it worked, e.g., https://misty-valley-1234.herokuapp.com/messages
. With GET requests it worked either way but with POST responses it only worked with the added path.
Use this extension for chrome. Allows to you request any site with ajax from any source. Adds to response 'Allow-Control-Allow-Origin: *' header
Replace get
with jsonp
:
$http.jsonp('http://mywebservice').success(function ( data ) {
alert(data);
});
}
It is a problem on the server side. You have to add your client address to your server exposed API. If you are using Spring frame work you can annotate @CrossOrgin from org.springframework.web.bind.annotation.CrossOrigin;
Eg : @CrossOrigin(origins = "http://localhost:8080")
If you are using chrome: try open chrome with the args to disable web security like you see here:
Disable same origin policy in Chrome
This is how it worked for me. For Windows users testing with Bracket and AngularJS
1) Go to your desktop
2) Right click on your desktop and look for "NEW" in the popup drop down dialog box and it will expand
3) Choose Shortcut
4) A dialog box will open
5) Click on Browse and look for Google Chrome.
6) Click Ok->Next->Finish and it will create the google shortcut on your desktop
7) Now Right Click on the Google Chrome icon you just created
8) Click properties
9) Enter this in the target path
"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security
10) Save it
11) Double click on your newly created chrome shortcut and past your link in the address bar and it will work.
'IT TIP' 카테고리의 다른 글
iOS 11에서 스크롤하지 않고 탐색 막대에 검색 막대 표시 (0) | 2020.11.19 |
---|---|
Linux에서 memcpy 성능 저하 (0) | 2020.11.05 |
Visual Studio Code의 사용자 및 시스템 설치 관리자의 차이점 (0) | 2020.11.05 |
개인 계정 대신 조직 계정에있는 GitHub 요점을 어떻게 만들 수 있습니까? (0) | 2020.11.05 |
Scala의 forSome 키워드는 무엇입니까? (0) | 2020.11.05 |