programing

요청된 리소스에 'Access-Control-Allow-Origin' 헤더가 없습니다(Angular).JS

sourcejob 2023. 3. 20. 23:11
반응형

요청된 리소스에 'Access-Control-Allow-Origin' 헤더가 없습니다(Angular).JS

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바에서 클릭하면 웹서비스가 정상적으로 동작합니다.문제 해결 방법제발 도와주세요!

Chrome Webstore에는 페이지에 다른 호스트에 액세스를 시도하는 비동기 호출이 있을 때 'Access-Control-Allow-Origin' 헤더를 추가하는 확장 기능이 있습니다.

확장자 이름은 "Allow-Control-Allow-Origin: *" 이며, 이 링크는 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi 입니다.

클라이언트 측에서는 Cors 요청을 Angular로 활성화할 수 있습니다.경유 JS

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";

또, Web 서비스도 설정할 필요가 있습니다.상세한 것은, 사용하고 있는 서버측의 언어에 의해서 다릅니다.네트워크 모니터링 도구를 사용하는 경우 처음에 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();

그런 다음 코르스를 사용하여 모델을 호출합니다.

컨트롤러에서는 글로벌스코프 또는 각 클래스에 대해 맨 위에 추가합니다.당신 마음대로 하세요.

 [EnableCorsAttribute("http://localhost:51003/", "*", "*")]

또한 이 데이터를 Angular에 푸시하면 .cshtml 파일도 호출됩니다.그렇지 않으면 데이터는 푸시되지만 뷰는 채워지지 않습니다.

(function () {
    "use strict";
    angular.module('common.services',
        ['ngResource'])
    .constant('appSettings',
    {
        serverPath: "http://localhost:51003/About"
    });
}());

//Replace URL with the appropriate path from production server.

이것이 도움이 되었으면 합니다.Entity Framework를 이해하는 데 시간이 걸렸고, CORS가 왜 그렇게 유용한지 이해하는데 시간이 좀 걸렸습니다.

저 같은 경우에는 Angular 코드를 많이 사용하는 MVC 앱 안에서 로컬 호스트의 WebAPI 서비스를 누르려고 했습니다.WebAPI 서비스는 http://localhost/myservice를 통해 Fiddler에서 정상적으로 동작했습니다.IIS Express(Visual Studio의 일부) 대신 IIS를 사용하도록 MVC 앱을 구성하자 어느 영역에든 CORS 관련 구성을 추가하지 않고 정상적으로 작동했습니다.

받았습니다

'Access-Control-Allow-Origin' 헤더가 없습니다.

에에에 URL 。 URL)을 제공하고 .https://misty-valley-1234.herokuapp.com/

경로를 했을 때 .https://misty-valley-1234.herokuapp.com/messagesGET 요구에서는 어느 쪽이든 동작하지만 POST 응답에서는 추가된 경로로만 동작합니다.

크롬에 이 확장자를 사용합니다.모든 소스에서 Ajax가 포함된 사이트를 요청할 수 있습니다.응답 'Allow-Control-Allow-Origin: *' 헤더에 추가합니다.

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related

get다음과 같이 설정합니다.

 $http.jsonp('http://mywebservice').success(function ( data ) {
    alert(data);
    });
}

서버측의 문제입니다.서버 노출 API에 클라이언트 주소를 추가해야 합니다.스프링 프레임워크를 사용하는 경우 org.springframework.web.bind.annotation에서 @CrossOrgin에 주석을 달 수 있습니다.크로스 오리진

예: @CrossOrigin (origins = "http://localhost:8080")

크롬을 사용하는 경우: 다음과 같이 args를 사용하여 크롬을 열어 웹 보안을 비활성화해 보십시오.

Chrome에서 동일한 원본 정책 사용 안 함

난 이렇게 됐어.괄호 및 각도로 테스트하는 Windows 사용자용JS

1) 데스크톱으로 이동

2) 바탕화면을 오른쪽 클릭하여 팝업 드롭다운 대화 상자에서 [NEW](새로 만들기)를 찾습니다.이 대화상자가 전개됩니다.

3) 숏컷 선택

4) 대화상자가 열립니다.

5) [참조]를 클릭하여 Google Chrome을 찾습니다.

6) [OK]-> [Next]-> [ Finish ]를 클릭하면 바탕화면에 구글 숏컷이 생성됩니다.

7) 방금 만든 Google Chrome 아이콘을 오른쪽 클릭합니다.

8) [속성]을 클릭합니다.

9) 대상 경로에 입력합니다.

"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security

10) 저장

11) 새로 작성한 Chrome 숏컷을 더블 클릭하여 주소창에서 링크를 통과하면 동작합니다.

언급URL : https://stackoverflow.com/questions/24134117/no-access-control-allow-origin-header-is-present-on-the-requested-resource-an

반응형