Cross-domain requests have always been a challenge in web programming, and in the past, most people tended to use JSONP to solve the problem. Now, however, we can consider a new feature in the--cors (cross-origin resource sharing). Client-created XMLHttpRequest objects need to use XmlHttpRequest2 objects for Cors,chrome, Firefox, and Safari, but for IE you need to use Xdomainrequest Opera does not currently support this feature, but it will soon be supported. Therefore, in the creation of objects, we have to first for different browsers for preprocessing: function createcorsrequest (Method, url) { Var xhr = new xmlhttprequest (); if ("Withcredentials"  IN XHR) The { // "Withcredentials" property is unique in XMLHTTPRequest2 xhr.open (method, url, true); } else if (typeof xdomainrequest != " Undefined ") { // detect xdomainrequest available xhr = New xdomainrequest (); xhr.open (Method, url); } else { // looks like cors is not supported at all xhr = null; }&nbsP; RETURN XHR;} Var xhr = createcorsrequest (' GET ', url);if (!XHR) { throw new error (' cors not supported ');} Event handling the original XMLHttpRequest object has only one event--onreadystatechange to notify all events, and now we have a lot more new than this event. Event description onloadstart* Triggers when a request is triggered when OnProgress reads and sends data when it occurs onabort* when a request is aborted, such as using Abort () Method onerror triggers when the request fails when the request is successful ontimeout triggers when the caller sets a timeout that has expired and is still unsuccessful onloadend* Trigger at end of request (whether successful or not) Note: Xdomainrequest with an asterisk is still not supported for IE. Data from http://www.w3.org/TR/XMLHttpRequest2/#events. In most cases, we only need to deal with OnLoad and onerror, just like this: xhr.onload = function () { var Responsetext = xhr.responsetext; console.log (responsetext); // continue with other code};xhr.onerror = function () { console.log (' there was an error! '); There's a little bit strange here. Although we can tell by OnError that the request has been wrong, we are unable to learn from the code any reason for the failure in the event processing. For example, Firefox fails to empty the ResponseText and returns a value of 0 as the state, which does not contain any errors in the specific case. Withcredentials Standard Cors Requests do not do anything with cookies, neither send nor change. If you want to change this, you need to set the withcredentials to TRUe. xhr.withCredentials = true; also, the server needs to set Access-control-allow-credentials to true when processing this request. This is a point we'll say later. The Withcredentials property makes the request contain all cookies from the remote domain, but it is worth noting that these cookies still adhere to the "same domain" guidelines, so you cannot read from the code in the Document.cookies or in response to the HTTP header. A send request request is sent through a simple send () method, and if any content is required in the request, it is only necessary to pass it as a parameter to send (). Once the server is configured OK, you will only have to deal with subsequent onload events, just as we are familiar with XHR. Take a look at a complete little code: // Create xhr Object Function createcorsrequest (Method, url) { var Xhr = new xmlhttprequest (); if ("Withcredentials"  IN XHR) { // for Chrome/safari/firefox. xhr.open (Method, url, true); } else if (typeof xdomainrequest != "undefined") { // for Ie xhr = new xdomainrequest (); xhr.open (Method, url); } else { // CORS &NBSP not supported; xhr = null; } return xhr;} Helper function for parsing the returned content Function gettitle (text) { return text.match (") [1];} Send Cors request function makecorsrequest () { // bibliographica.org is a cors-enabled var url = ' http://bibliographica.org/'; var xhr = Createcorsrequest (' GET ', url); if (!XHR) { alert (' CORS not supported '); return; } // response handling 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 ();} A cors request on the server may contain multiple HTTP headers, and even multiple requests are actually sent, which is usually transparent to the developer of the client. Because the browser is already responsible for implementing the most critical part of Cors, the backend script on the server needs to be handled by ourselves, so we need to know exactly what the server has received from the browser. Let's take a look at the flowchart. Cors Flowchart Cors Classification cors can be divided into two types: simple request complex request a simple request is roughly as follows: The HTTP method is one of the following headgetposthttp header contains acceptaccept-languagecontent-languagelast-event- Idcontent-type, but can only be one of the following application/x-www-form-urlencodedmultipart/form-datatext/plain any request that does not meet the above requirements is considered a complex request. A complex request has not only a request containing the content of the communication, but also a pre-request (Preflight request). Simple request to figure out how complex requests differ from simple requests, let's start by looking at how simple requests are handled. javascript: var url = ' http://alice.com/cors '; Var xhr = createcorsrequest (' GET ', url); Xhr.send (); HTTP Request: get /cors http/1.1origin: http://api.alice.comhost: api.bob.comaccept-language: en-usconnection: keep-aliveuser-agent: mozilla/5.0 ... The sending of a simple request is not much different from the normal XHR in code, but the HTTP header always contains information about a domain (Origin). The domain contains the protocol name, address, and an optional port. But this one is actually sent by the browser andNot what the developer code can touch. HTTP response: access-control-allow-origin: http://api.bob.comaccess-control-allow-credentials: Trueaccess-control-expose-headers: foobarcontent-type: text/html; charset=utf-8 in response, COR-related projects are all prefixed with "access-control-", the meaning of which is as follows: Access-control-allow-origin (must include)- must not be omitted, otherwise the request will be processed by failure. This controls the visible range of the data and, if you want the data to be visible to anyone, fill in the "*". Access-control-allow-credentials (optional) – This indicates whether the request contains cookies, with only one optional value: True (must be lowercase). If you do not include cookies, please omit the entry instead of filling in false. This item should be consistent with the Withcredentials attribute in the XmlHttpRequest2 object, that is, if the item is true;withcredentials False when Withcredentials is true, omit the item from writing. The reverse causes the request to fail. Access-control-expose-headers (optional) – This item determines the additional information that the getResponseHeader () method in the XmlHttpRequest2 object can obtain. Typically, the getResponseHeader () Method can only obtain the following information: Cache-controlcontent-languagecontent-typeexpireslast-modifiedpragma When you need access to additional information, You need to fill in this item and separate it with a comma. However, there are still some problems with the implementation of this item in the browser, please see the bug section at the end of this article. Complex requests, if only simple requests, are not a big deal without cors, but Cors's complex requests make cors even more useful. Simply put, any request that does not meet the requirements of the above simple request is a complex request. For example, you need to send HTTP actions such as put, delete, or send Content-type: applicThe content of the Ation/json. Complex requests appear to be similar to simple requests on the surface, but in fact the browser sends more than one request. One of the first to send is a "pre-request", which, as a server, also needs to return "pre-response" as a response. A pre-request is actually a permission request to the server, and only if the pre-request returns successfully does the actual request begin. javascript: var url = ' http://alice.com/cors '; Var xhr = createcorsrequest (' PUT ', url); Xhr.setrequestheader ( ' x-custom-header ', ' value '); Xhr.send (); Pre-Request: OPTIONS /cors HTTP/1.1Origin: http://api.alice.comAccess-Control-Request-Method: putaccess-control-request-headers: x-custom-headerhost: api.bob.comaccept-language: en-usconnection: keep-aliveuser-agent: mozilla/5.0. Pre-request is sent as options, which also contains fields, It also contains two cors-specific content:access-control-request-method – The content is the kind of actual request that can be a simple request such as GET, post, or put, delete, and so on. access-control-request-headers – the item is a comma-delimited list of headers used by complex requests. Obviously, this pre-request actually sends a permission request for the actual request that follows, and in the content returned by the pre-response, the server should reply to the two items so that the browser can determine whether the request was completed successfully. For example, a pre-request may have received the following response from the server: access-control-allow-origin: http://api.bob.comaccess-control-allow-methods: get, post, putaccess-control-allow-headers: x-custom-headercontent-type: Text/html; charset=utf-8 to see possible items in the pre-response: Access-control-allow-origin (required) – as with simple requests, a domain must be included. Access-control-allow-methods (must include) – this is a access-control-request-method reply to the pre-request, which will be a comma-delimited list. Although the client may only request a method, the server can still return all allowed methods for the client to cache. Access-control-allow-headers (must be included when Access-control-request-headers is included in the pre-request) – This is a access-control-request-headers reply to the pre-request, as above is a comma-delimited list that can return all supported headers. Access-control-allow-credentials (optional) – is the same as a simple request. Access-control-max-age (optional) – cache time in seconds. Pre-requested delivery is not a free lunch and should be cached whenever possible. Once the pre-response is as scheduled and the requested permission is satisfied, the actual request begins to be sent. Actual Request: put /cors http/1.1origin: http://api.alice.comhost: api.bob.comx-custom-header: valueaccept-language: en-usconnection: keep-aliveuser-agent: mozilla/5.0. Actual response: Access-control-allow-origin: http://api.bob.comcontent-type: text/html; charset=utf-8 ifThe required permissions on the pre-request server is not allowed, then the server can return a normal HTTP response, for example: // error - no cors headers, this is an invalid request! Content-type: text/html; charset=utf-8 such a return because it does not meet the needs of the client, so the client will directly to the request to fail, although not very mike, but it is in line with our actual. At this point, if the client's OnError event has a listener function, it will be triggered, and the browser's console window will output: xmlhttprequest cannot load http:// api.alice.com. origin http://api.bob.com is not allowed by Access-control-allow-origin. Unfortunately, the browser does not give a detailed error condition, just to tell us that it was a mistake. Security issues cross-domain requests are always a headache in web page security, Cors provides a cross-domain request scheme, but does not provide adequate safeguards for secure access, if you need the absolute security of information, do not rely on cors in the authority system, should use more other measures to protect, Like OAuth2. Known Issues Cors is a more "new" scheme in the web, so that the big page parsing engines have not been implemented perfectly. The following are known issues as of November 13, 2011: The getAllResponseHeaders () method failed to obtain the information requested in the Access-control-expose-headers. In Chrome/safari, only simple heads can be read, others cannot be obtained, and in Firefox, no information is available. (Firefox bugzilla/webkit bugzilla) in Safari, a complex request with Get, POST method is sent without sending a pre-request link. OnError triggers when statustext gets nothing. Opera still does not support cors up to 11.60, but it will be supported in 12 (opera core concerns – cors goes mainline).
Mobile-side cross-domain CORS HTML5