HTML5-CORS

Cross-origin resource sharing (CORS) 웹 브라우저에서 다른 도메인의 제한된 리소스를 허용하는 메커니즘입니다.

html5 데모 섹션에서 HTML5 동영상 플레이어 를 클릭한다고 가정 해 보겠습니다 . 카메라 권한을 요청합니다. 사용자가 권한을 허용하면 카메라 만 열리거나 웹 응용 프로그램 용 카메라가 열리지 않습니다.

CORS 요청하기

여기서 Chrome, Firefox, Opera 및 Safari는 모두 XMLHttprequest2 개체를 사용하고 Internet Explorer는 유사한 XDomainRequest 개체 인 개체를 사용합니다.

function createCORSRequest(method, url) {
   var xhr = new XMLHttpRequest();
   
   if ("withCredentials" in xhr) {
      
      // Check if the XMLHttpRequest object has a "withCredentials" property.
      // "withCredentials" only exists on XMLHTTPRequest2 objects.
      xhr.open(method, url, true);
   } else if (typeof XDomainRequest != "undefined") {
      
      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
      xhr = new XDomainRequest();
      xhr.open(method, url);
   } else {
      
      // Otherwise, CORS is not supported by the browser.
      xhr = null;
   }
   return xhr;
}

var xhr = createCORSRequest('GET', url);

if (!xhr) {
   throw new Error('CORS not supported');
}

CORS의 이벤트 핸들

Sr. 아니. 이벤트 핸들러 및 설명
1

onloadstart

요청을 시작합니다.

2

onprogress

데이터를로드하고 데이터를 보냅니다.

onabort

요청 중단

4

onerror

요청이 실패했습니다

5

onload

성공적으로로드 요청

6

ontimeout

요청이 완료되기 전에 시간 초과가 발생했습니다.

7

onloadend

요청이 성공하거나 실패한 경우

onload 또는 onerror 이벤트의 예

xhr.onload = function() {
   var responseText = xhr.responseText;
   
   // process the response.
   console.log(responseText);
};

xhr.onerror = function() {
   console.log('There was an error!');
};

핸들러가있는 CORS의 예

아래 예제는 makeCorsRequest () 및 onload 핸들러의 예제를 보여줍니다.

// Create the XHR object.
function createCORSRequest(method, url) {
   var xhr = new XMLHttpRequest();
   
   if ("withCredentials" in xhr) {
      
      // XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);
   } else if (typeof XDomainRequest != "undefined") {
      
      // XDomainRequest for IE.
      xhr = new XDomainRequest();
      xhr.open(method, url);
   } else {
      
      // CORS not supported.
      xhr = null;
   }
   return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
   return text.match('<title>(.*)?</title>')[1];
}

// Make the actual CORS request.
function makeCorsRequest() {
   
   // All HTML5 Rocks properties support CORS.
   var url = 'http://www.tutorialspoint.com';
   
   var xhr = createCORSRequest('GET', url);
   
   if (!xhr) {
      alert('CORS not supported');
      return;
   }
   
   // Response handlers.
   xhr.onload = function() {
      var text = xhr.responseText;
      var title = getTitle(text);
      alert('Response from CORS request to ' + url + ': ' + title);
   };
   
   xhr.onerror = function() {
      alert('Woops, there was an error making the request.');
   };
   xhr.send();
}