Troubleshoot cross-domain issues with AJAX requests

Source: Internet
Author: User
Tags http authentication send cookies

from:53333775

As mentioned in the previous article, because of the browser's homologous policy, so that the AJAX request can only be sent to the same-origin URL, or error. In addition to setting up a server proxy, such as Nginx (the browser requests the same origin server, and then the latter requests the external service), there are three ways to circumvent this limitation:

First, JSONP

Jsonp is a common method for server-to-client cross-origin communication. The biggest feature is simple to use, old browsers all support, server transformation is very small.

The basic idea is that Web pages request JSON data from the server by adding a <script> element that is not subject to the same-origin policy; After the server receives the request, it returns the data in a callback function with the specified name.

First, the Web page dynamically inserts the <script> element, which makes the request to the cross-origin URL:

[JavaScript]View PlainCopy
  1. function Addscripttag (SRC) {
  2. var script = document.createelement (' script ');
  3. Script.setattribute ("type","Text/javascript");
  4. SCRIPT.SRC = src;
  5. Document.body.appendChild (script);
  6. }
  7. Window.onload = function () {
  8. Addscripttag (' Http://example.com/ip?callback=foo ');
  9. }
  10. function foo (data) {
  11. Console.log (' Your public IP address is: ' + data.ip);
  12. };

The above code makes a request to the server example.com by dynamically adding the <script> element. Note that the query string for the request has a callback parameter that specifies the name of the callback function, which is required for JSONP.

After the server receives this request, it returns the data in the parameter position of the callback function:

  

Because of the script requested by the <script> element, it runs directly as code. At this point, as soon as the browser defines the Foo function, the function is called immediately. JSON data as a parameter is treated as a JavaScript object, not as a string, so the steps to use Json.parse are avoided.

Second, WebSocket

WebSocket is a communication protocol that uses ws://(non-encryption) and wss://(encryption) as the protocol prefix. This protocol does not implement the same-origin policy, as long as the server support, you can cross-source communication through it. The following is an example of the header information sent by the browser to the WebSocket request:

  

In the above code, one of the fields is origin, which represents the request source (origin), which is the originating domain. It is because of the origin of this field, so WebSocket did not implement the same-origin policy. This is because the server can determine whether to license this communication based on this field. If the domain name is in the whitelist, the server responds as follows:

  

Third, CORS

Cors is an abbreviation for cross-origin resource sharing (Cross-origin Resource sharing). It is the standard of the standards and is the fundamental solution to cross-source Ajax requests. Cors allows any type of request compared to JSONP can only send a GET request.

It allows the browser to issue XMLHttpRequest requests to cross-origin servers, overcoming the limitation that Ajax can only use the same origin. This article describes the internal mechanisms of cors in detail:

3.1 Introduction

Cors requires both browser and server support. Currently, all browsers support this feature, IE browser cannot be less than IE10.

The entire cors communication process is done automatically by the browser and does not require user involvement. For developers, Cors Communication is no different from the same-Origin Ajax communication, and the code is exactly the same. Once the browser discovers that the AJAX request crosses the source, it automatically adds some additional header information, sometimes with an additional request, but the user does not feel it.

Therefore, the key to achieving cors communication is the server. As long as the server implements the Cors interface, it can communicate across the source.

3.2 Two types of requests

The browser divides the Cors requests into two categories: simple request and non-simple (Not-so-simple request). As long as the following two conditions are met, it is a simple request:

  

It is a non-simple request that does not satisfy the above two conditions at the same time. The browser does not handle these two requests in the same way.

3.3 Simple Request Basic process

For simple requests, the browser makes a cors request directly. Specifically, in the header information, add an Origin field. Here is an example where the browser discovers that the cross-origin Ajax request is a simple request and automatically adds an origin field to the header information:

  

In the header information above, the Origin field is used to indicate which source (protocol + domain + port) The request came from. Based on this value, the server decides whether to agree to this request.

If origin specifies a source that is not within the scope of the license, the server returns a normal HTTP response. The browser found that the header information for this response did not contain the Access-control-allow-origin field (see below), and knew that an error occurred, thus throwing a bug that was captured by the XMLHttpRequest OnError callback function. Note that this error cannot be identified by the status code because the status code of the HTTP response is likely to be 200.

If the domain name specified by origin is within the scope of the license, the response returned by the server will have more than a few header information fields:

  

Among the header information above, there are three fields related to cors requests, beginning with access-control-:

Access-control-allow-origin: This field is required. Its value is either the value of the Origin field at the time of the request, or a * that represents the request to accept any domain name.

Access-control-allow-credentials: This field is optional. Its value is a Boolean value that indicates whether the cookie is allowed to be sent. By default, cookies are not included in Cors requests. Set to true, which means that the server explicitly permits the cookie to be included in the request and sent to the server. This value can only be set to TRUE if the server does not send a cookie to the browser, delete the field.

Access-control-expose-headers: This field is optional. Cors request, the XMLHttpRequest object's getResponseHeader () method can only get 6 basic fields: Cache-control, Content-language, Content-type, Expires, Last-modified, Pragma. If you want to get the other fields, you must specify them in the Access-control-expose-headers. The above example specifies that getResponseHeader (' FooBar ') can return the value of the FooBar field.

Withcredentials Property

As mentioned above, cors requests do not send cookies and HTTP authentication information by default. If you want to send cookies to the server, on the one hand, the server agrees, specify the Access-control-allow-credentials field:

  

On the other hand, the developer must open the Withcredentials attribute in an AJAX request:

  

Otherwise, the browser is not sent even if the server agrees to send a cookie. Alternatively, the server requires a cookie to be set and the browser will not process it. However, if you omit the Withcredentials setting, some browsers will still send cookies together. At this point, you can explicitly turn off withcredentials:

  

It is important to note that if you are sending Cookie,access-control-allow-origin you cannot set an asterisk, you must specify an explicit domain name that is consistent with the requested page. At the same time, the cookie still follows the same-origin policy, only the cookie that is set by the server domain name is uploaded, the cookie of other domain name is not uploaded, and the Document.cookie in the original page code (cross source) cannot read the cookie under the server domain name.

3.4 Non-simple request pre-test request

Non-trivial requests are requests that have special requirements for the server, such as a put or delete, or the type of the Content-type field is Application/json.

A cors request that is not a simple request, adds an HTTP query request, called a preflight request (preflight), before the formal communication.

The browser asks the server first, whether the domain name in which the current page resides is in the server's license list, and which HTTP verbs and header information fields can be used. The browser will issue a formal XMLHttpRequest request only if a positive reply is received, otherwise it will be an error.

Here is a JavaScript script for a browser:

  

In the above code, the HTTP request method is put, and a custom header information X-custom-header is sent. The browser discovers that this is a non-trivial request, and automatically issues a "preflight" request, requiring the server to confirm that it can request it. Here is the HTTP header information for this preflight request:

  

The request method for "Preflight" Requests is the options, indicating that the request is for questioning. Header information, the key field is origin, which indicates which source the request came from. In addition to the Origin field, the header information for a preflight request consists of two special fields:

Access-control-request-method: This field is required to list which HTTP methods are used by the browser's cors request, and the above example is put.

Access-control-request-headers: This field is a comma-delimited string that specifies the header information field that the browser cors request will send extra, and the example above is X-custom-header.

Responses to pre-test requests

After the server receives a "preflight" request, after checking the origin, Access-control-request-method, and Access-control-request-headers fields, the acknowledgment allows cross-origin requests to respond:

  

In the HTTP response above, the key is the Access-control-allow-origin field, which indicates that http://api.bob.com can request data. The field can also be set to an asterisk, which means agreeing to any cross-origin request:

  

If the browser negates the "preflight" request, a normal HTTP response is returned, but there is no cors-related header information field. At this point, the browser will assume that the server does not agree with the preflight request and therefore trigger an error that is captured by the onerror callback function of the XMLHttpRequest object. The console will print the following error message:

  

Other Cors-related fields for the server response are as follows:

  

Access-control-allow-methods: This field is required, and its value is a comma-delimited string that indicates the method that the server supports for all cross-domain requests. Note that all supported methods are returned, not just the one requested by the browser. This is to avoid multiple "preflight" requests.

Access-control-allow-headers: If the browser request includes a access-control-request-headers field, the Access-control-allow-headers field is required. It is also a comma-delimited string that indicates all header information fields supported by the server, not limited to the fields requested by the browser in preflight.

Access-control-allow-credentials: This field has the same meaning as a simple request.

Access-control-max-age: This field is optional to specify the validity period for this preflight request, in seconds. In the result, the validity period is 20 days (1.728 million seconds), which allows the cache to be cached for 1.728 million seconds (that is, 20 days), during which time there is no need to issue another preflight request.

browser's normal request and response

Once the server passes the "preflight" request, each subsequent browser's normal cors request, like a simple request, will have an Origin header information field. Server response, there will also be a Access-control-allow-origin header information field.

Following is the "preflight" request, the browser's normal cors request:

  

The Origin field of the header information above is automatically added by the browser. The following is a normal response from the server:

  

In the above header information, the Access-control-allow-origin field is necessarily included in each response.

Iv. Summary

This paper mainly introduces the cross-domain problem of solving the AJAX request, the common way is JSONP and cors two kinds of solution. Cors uses the same purpose as JSONP, but is more powerful than JSONP. JSONP only supports get requests, and Cors supports all types of HTTP requests. The advantage of JSONP is that it supports older browsers and can request data from sites that do not support cors.

Troubleshoot cross-domain issues with AJAX requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.