Cross-Origin Resource Sharing 1. what is cross-origin resource sharing?
CORS (Cross-Origin Resource Sharing) is the basic idea of a website's Resource access to another Resource on a different Origin site, it is to use a custom HTTP header to allow the browser to communicate with the server, so as to determine whether the request or response is successful or failed.
2. why cross-origin resource sharing?
Due to cross-origin security policy restrictions, XHR enables ajax communication. an XHR object can only access resources in the same domain as the page containing it. In actual application Cross-origin requests are required to load external style sheet files, external images loaded by tags, and external script files loaded by script tags.
3. CORS implementation
Implementation of CORS by IE
Request cross-origin files
var xdr = new XDomainRequest();xdr.onload = function(){ alert(xdr.responseText);};xdr.onerror=function(){ alert("an error occurred");};xdr.open("get", "http://www.baidu.com/resource/");xdr.send();
Server Files
Header ("Access-Control-Allow-Origin: http://www.baidu.com/resource/"); // The corresponding allowed Source header ("Access-Control-Allow-Method: http: POST, GET "); // allowed method header (" Access-Control-Allow-Header: http: NCZ "); // allowed header ("Access-Control-Max-Age: http: 86400"); // request cache durationImplementation of CORS in firefox, safari, and chrome
var xhr=new createXHR();xhr.onreadystatechange=function(){ if(xhr.readystate==4){ if((xhr.status>=200&&xhr.status<300)||xhr.status==304){ alert(xhr.responseText); } }else{ alert("request was failed:"+xhr.status); }};xhr.open("get", "http://www.baidu.com/resource/");xdr.send();4. other cross-origin Technologies
JSONP (JSON with Padding filling JSON or parameter JSON)
SONP consists of two parts: callback function and data. The callback function is the function that should be called on the page when the response arrives, and the data is the JSON data passed into the callback function.
For example: