Ajax cross-domain principles and solutions

Source: Internet
Author: User
Tags script tag

Description

Cross-domain is mainly due to the browser "homologous strategy" caused by a variety of types, this article mainly discusses the AJAX request cross-domain problem

Objective

It is highly recommended to read the articles in the reference source to quickly help understand the principles of cross-domain

Reference sources

This article references the following sources

    • Browser homology policy and its avoidance method (Nanyi)
    • Cross-domain resource sharing CORS detailed (Nanyi)
What is a cross-domain

To better understand the principle of cross-domain, you can read the article in the reference source, which explains the principle of cross-domain in detail.

The performance of the Ajax cross-domain

Ajax requests, if there is a cross-domain phenomenon, and does not resolve, there will be the following performance

    • The first phenomenon: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource , and The response had HTTP status code 404 ,

      This occurs for the following reasons:

      • This AJAX request is a "non-trivial request", so a pre-check request (OPTIONS) is sent before the request
      • The server-side background interface does not allow the options request, resulting in the inability to find the corresponding interface address
    • The second phenomenon: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource and The response had HTTP status code 405 ,

      This behavior differs from the first, in which case the background method allows the options request, but some configuration files (such as security Configuration) block the options request, which can cause this behavior

    • The third phenomenon: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource ,

      This behavior differs from the first and second, in which case the server-side background allows the options request, and the interface allows the options request, but there is a mismatch in the head match, such as the Origin header check mismatch, such as the lack of some head support ( such as the common X-requested-with head), then the server will return response to the front end, the front end detects this trigger Xhr.onerror, leading to the front console error

    • Note that requests for cross-domain analysis are typically cross-domain in AJAX requests, and there is no problem with normal HTTP requests
The principle of cross-domain

The reason why the AJAX request cross-domain error problem, the main reason is because the browser "homologous policy", you can refer to the browser Origin policy and its avoidance method (Nanyi)

How to troubleshoot cross-domain issues

The general Ajax cross-domain solution is solved by JSONP or Cros, such as the following (note that Ajax cross-domain is only part of the browser "same-Origin policy", and other cookies cross-domain iframe across domains, Localstorage cross-domain, etc. not introduced here)

Jsonp Way to solve cross-domain problems

Jsonp solving cross-domain issues is an older scenario (not recommended in practice), here's a brief introduction

In real-world projects, if you want to use JSONP, you will typically use a class library such as JQ to encapsulate JSONP for AJAX requests.

Implementation principle

Jsonp is able to solve cross-domain scenarios primarily because <script> scripts have cross-domain capabilities, and Jsonp is leveraging this. Specific principles

Implementation process

The implementation steps of JSONP are as follows (refer to the articles in the source)

    • Client page Web pages request JSON data from the server by adding a <script> element that is not restricted by the same-origin policy
      function Addscripttag (src) {  var script = document.createelement (' script ');  Script.setattribute ("type", "Text/javascript");  SCRIPT.SRC = src;  Document.body.appendChild (script);} Window.onload = function () {  addscripttag (' Http://example.com/ip?callback=foo ');} function foo (data) {  Console.log (' response data: ' + json.stringify (data));};

      When requested, the interface address is the SRC of the built-in script tag, so that when the script tag is built, the final SRC is the content returned by the interface

    • The interface corresponding to the server adds a function wrapping layer outside the return parameter
      Foo ({  "test": "TestData"});
    • 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.

      Note that the general JSONP interface and normal interface return data is different, so if the interface to do jsono compatibility, need to determine if there is a corresponding callback keyword parameters, if there is a JSONP request, return JSONP data, otherwise return normal data

Use note

Based on the implementation principle of JSONP, so JSONP can only be "GET" request, not more complex post and other requests, so in that case, you have to refer to the following Cros to solve the cross-domain

Cros resolving cross-domain issues

Cors is a universal standard, with the name "cross-domain resource sharing" (cross-origin resource sharing). It allows the browser to issue XMLHttpRequest requests to cross-origin servers, overcoming the limitation that Ajax can only use the same origin.

Basically all browsers now implement the Cors standard, in fact, almost all of the browser Ajax requests are based on the cors mechanism, but it is possible that the front-end developers do not care about it (so that its implementation in the Cros solution is mainly to consider how to implement the background of the problem).

Highly recommended read cross-domain resource sharing CORS details (Nanyi)

Cros Request principle

Implementation principles such as (simplified version)

    • How can I tell if it is a simple request?

      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.

      • The request method is one of the following three methods:

        Head,get,post

      • The header information for HTTP does not exceed the following fields:

        Accept,accept-language,content-language,last-event-id,content-type: Limited to three values application/x-www-form-urlencoded, Multipart/form-data, Text/plain

PHP Background Configuration

PHP backend configuration is almost all the simplest in the background, follow the steps below

    • First step: Configure PHP Background to allow cross-domain

      Two basic information mainly for cross-domain Cros configuration, origin and headers

    • Step Two: Configure the Apache Web server cross-domain

      Typically every Web server is installed to configure cross-domain information

      The above picture is seen on a certain website and is used directly. But the specific source address has not been found ...

Java Background configuration

The Java background is relatively simple to configure, just follow the steps below

  • First step: Get the Dependent jar package

    Download Cors-filter-1.7.jar, Java-property-utils-1.9.jar these two library files into the Lib directory. (placed under the webcontent/web-inf/lib/of the corresponding project)

  • Step two: If the project was built with MAVEN, add the following dependencies to Pom.xml: (non-maven please ignore)
    <dependency><groupid>com.thetransactioncompany</groupid><artifactid>cors-filter</ artifactid><version>[version]</version></dependency>

    Where the version should be the latest stable version, Cros filter

  • Step three: Add the Cros configuration to the project's Web. XML (App/web-inf/web.xml)
    <!--cross-domain configuration--><filter><!--The CORS filter with parameters--><filter-name>cors</filter-name ><filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class><!--Note:all  Parameters is options, if omitted the CORS Filter would fall back to the respective default values. --><init-param><param-name>cors.allowgenerichttprequests</param-name><param-value> True</param-value></init-param><init-param><param-name>cors.alloworigin</param-name ><param-value>*</param-value></init-param><init-param><param-name> cors.allowsubdomains</param-name><param-value>false</param-value></init-param>< Init-param><param-name>cors.supportedmethods</param-name><param-value>get, HEAD, POST, options</param-value></init-param><init-param><param-name>cors.supportedheaders</ Param-name><param-value>Accept, Origin, X-requested-with, Content-type, Last-modified</param-value></init-param><init-param ><param-name>cors.exposedHeaders</param-name><!--Here you can add some of your own exposure headers--><param-value >x-test-1, x-test-2</param-value></init-param><init-param><param-name> cors.supportscredentials</param-name><param-value>true</param-value></init-param>< init-param><param-name>cors.maxage</param-name><param-value>3600</param-value></ init-param></filter><filter-mapping><!--CORS Filter Mapping--><filter-name>cors</ Filter-name><url-pattern>/*</url-pattern></filter-mapping>

    Please note that the above configuration file is placed in front of the Web. XML, as the first filter exists (can have multiple filter)

NET Background configuration

. NET background configuration compared to the previous two, a bit more complex, you can refer to the following steps

    • First Step: Site Configuration

      Open the Control Panel, select Administrative Tools, select IIS, right-click your Web site, select Browse, open the directory where the Web site is located, open the Web. config file with Notepad, add the following configuration information, restart the site

      Please note that older, if the configuration still problems, you can consider adding more headers allow, such as

      "Access-control-allow-headers": "X-requested-with,content-type,accept"

      Or add more custom headers

    • Step two: Other more configurations

      If there is a cross-domain problem after the first step, it is possible that the interface in the background is not running the options request, [System.Web.Mvc.HttpPost] so remove it and let the interface support more requests

Faqmulti value ' *,* ' problem
    • Reason for occurrence

      The problem arises because the HTTP header information for the background response is two access-control-allow-origin:*. Common in. NET background (typically an origin is configured in Web. config, and then the origin is added manually in the code)

    • Performance phenomena

    • Workaround

      Remove the manually added origin:* from the code (note that if you remove the configuration from config, it can cause cross-domain problems, only the line that you add in the code is removed ...)

Ajax cross-domain principles and solutions

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.