Home  >  Article  >  Web Front-end  >  The most comprehensive solution to cross-domain ajax

The most comprehensive solution to cross-domain ajax

韦小宝
韦小宝Original
2018-03-08 16:00:341823browse

When I first started learning JavaScript, I didn’t know what ajax cross-domain was, but I often heard some big guys talking about ajax cross-domain issues across domains. I must have classmates like me. , so let’s take a look today at what exactly ajax cross-domain is, and what are the methods to solve ajax cross-domain!

Preface

Regarding cross-domain, there are N types. This article only focuses on ajax request cross-domain (, ajax cross-domain only belongs to browsing Part of the "same origin policy" of the server, others include Cookie cross-domain, iframe cross-domain, LocalStorage cross-domain, etc. (not introduced here), the content is roughly as follows:

1. What Is ajax cross-domain

##Principle

Performance (sorted out some encounters problems and solutions)

2. How to solve ajax cross-domain

JSONP method

CORS method

Proxy request method

3. How to analyze ajax cross-domain

http packet capture analysis

Some examples

What is ajax cross-domain

The principle of cross-domain ajax

The main reason why ajax has a cross-domain request error problem is because of browsing For the "same origin policy" of the browser, you can refer to

Browser origin policy and its circumvention methods

CORS request principle

CORS is a W3C standard, the full name is "Cross-origin resource sharing" (Cross-origin resource sharing). It allows the browser to issue XMLHttpRequest requests to cross-origin servers, thereby overcoming the limitation that AJAX can only be used from the same origin.

Basically all current browsers have implemented the CORS standard. In fact, almost all browser ajax requests are based on the CORS mechanism, but front-end developers may not care about it (so in fact The current CORS solution mainly considers how to implement the background).

Regarding CORS, it is highly recommended to read


Detailed explanation of CORS for cross-domain resource sharing

In addition, an implementation is also compiled here Schematic (simplified version):

The most comprehensive solution to cross-domain ajax

#How to determine whether it is a simple request?Browsers divide CORS requests into two categories: simple requests (simple requests) and non-so-simple requests (not-so-simple requests). As long as the following two conditions are met at the same time, it is a simple request.

1.

Request method is one of the following three methods: HEAD, GET, POST

2. HTTP header information Do not exceed the following fields:

1. Accept 2. Accept-Language

3. Content-Language

4. Last-Event-ID

5. Content-Type (limited to three values ​​application/x-www-form-urlencoded, multipart/form-data, text/plain)

Whenever different If the above two conditions are met, it is a non-simple request.

Ajax cross-domain performance

To be honest, I compiled an article at first and then used it as a solution, but later I found that it was still Many people still don't know how. We have no choice but to debug it which is time-consuming and labor-intensive. However, even if I analyze it, I will only judge whether it is cross-domain based on the corresponding performance, so this is very important. When making an ajax request, if there is a cross-domain phenomenon and it is not resolved, the following behavior will occur: (Note, it is an ajax request. Please do not say why http requests are OK but ajax is not, because ajax is accompanied by Cross-domain, so just http request ok is not enough)

Note: Please see the title position for specific back-end cross-domain configuration.

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

The most comprehensive solution to cross-domain ajax

The reasons for this situation are as follows:

1. This ajax request is "Not a simple request", so a preflight request (OPTIONS) will be sent before the request

2. The server-side background interface does not allow OPTIONS requests, resulting in the inability to find the corresponding interface address

Solution: The backend allows options requests

Second phenomenon:No 'Access-Control-Allow-Origin' header is present on the requested resource, andThe response had HTTP status code 405


The most comprehensive solution to cross-domain ajax

This phenomenon is different from the first one. In this case, the background method allows OPTIONS requests, but some

configuration files (such as security configuration) block OPTIONS requests, which causes this phenomenon.

Solution: Close the corresponding security configuration on the backend

The third phenomenon:

No 'Access-Control-Allow-Origin' header is present on the requested resource , and status 200

The most comprehensive solution to cross-domain ajax

##This phenomenon is different from the first and second , In this case, the server-side background allows OPTIONS requests, and the interface also allows OPTIONS requests, but there is a mismatch when the headers match.

For example, the origin header check does not match, for example, some headers are missing. Support (such as the common X-Requested-With header), and then the server will return the response to the front-end. After the front-end detects this, it will trigger XHR.onerror, causing the front-end console to report an error

Solution: The backend adds corresponding header support

Fourth phenomenon:

heade contains multiple values ​​'*,*'

The most comprehensive solution to cross-domain ajax

##The phenomenon is that the http header information of the background response has two Access-Control-Allow-Origin:*

To be honest, this kind of problem occurs The main reason is that people who perform cross-domain configuration do not understand the principle, resulting in repeated configurations, such as:

1. Commonly seen in the .net background (usually origin is configured once in web.config, and then again in the code Manually added an origin (for example, the code manually sets the return *))

2. Commonly used in the .net background (set Origin:* in IIS and the project's webconfig at the same time)

Solution (one-to-one correspondence):

1. It is recommended to delete the * manually added in the code and only use the ones in the project configuration

2 , it is recommended to delete the configuration under IIS*, and only use the configuration in the project configuration

How to solve ajax cross-domain

General Ajax cross-domain solution is solved through JSONP or CORS, as follows: (Note that JSONP is almost no longer used, so just understand JSONP)

JSONP solution Cross-domain problems

jsonp is a relatively old solution to solve cross-domain problems (not recommended in practice). Here is a brief introduction (if you want to use JSONP in actual projects, you will generally use JQ and other class libraries that encapsulate JSONP to make ajax requests)

Implementation principle

The reason why JSONP can be used to solve cross-domain problems The main reason for this solution is that <script> scripts have cross-domain capabilities, and JSONP takes advantage of this to achieve it. The specific principle is shown in the figure</script>

Implementation process

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

1. The client web page requests JSON from the server by adding a <script> element Data, this approach is not restricted by the same-origin policy</script>

function addScriptTag(src) {
  var script = document.createElement(&#39;script&#39;);
  script.setAttribute("type","text/javascript");
  script.src = src;
  document.body.appendChild(script);
}

window.onload = function () {
  addScriptTag(&#39;http://example.com/ip?callback=foo&#39;);
}

function foo(data) {
  console.log(&#39;response data: &#39; + JSON.stringify(data));
};

When requesting, the interface address is used as the src of the built script tag. In this way, when the script tag is built, the final src is returned by the interface Content

2. The corresponding interface on the server side adds a function wrapping layer outside the return parameter

foo({
  "test": "testData"
});

3. Since the script requested by the <script> element is run directly as code. At this time, as long as the browser defines the foo function, the function will be called immediately. JSON data as arguments are treated as <a href="http://www.php.cn/js/js-jsref-tutorial.html" target="_blank">JavaScript objects, not strings, thus avoiding the step of using JSON.parse. </script>

Note that there is a difference between the data returned by the general JSONP interface and the ordinary interface. Therefore, if the interface is to be JSONO compatible, it needs to be judged whether there is a corresponding callback keyword parameter. If so, it is a JSONP request and JSONP is returned. data, otherwise return ordinary data

Usage Notes

Based on the implementation principle of JSONP, so JSONP can only be a "GET" request, and cannot perform more complex POST and other request, so if you encounter that situation, you have to refer to the following CORS to solve cross-domain problems (so it has basically been eliminated now)

CORS solves cross-domain problems

The principle of CORS has been introduced above. What is mainly introduced here is how the backend should be configured to solve problems in actual projects (because a large number of project practices are solved by the backend). Here are some common backend solutions:

PHP backend configuration

PHP backend configuration is almost the simplest of all backends , just follow the steps below:

The first step: Configure the Php background to allow cross-domain

<?php
header(&#39;Access-Control-Allow-Origin: *&#39;);
header(&#39;Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept&#39;);
//主要为跨域CORS配置的两大基本信息,Origin和headers

The second step: Configure the Apache web server cross-domain (in httpd.conf)

Original code

<Directory />
    AllowOverride none
    Require all denied
</Directory>

Changed to the following code

<Directory />
    Options FollowSymLinks
    AllowOverride none
    Order deny,allow
    Allow from all
</Directory>

Node.js background configuration (express framework)

Node The .js backend is also relatively simple to configure. Just use express to configure as follows:

app.all(&#39;*&#39;, function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", &#39; 3.2.1&#39;)
        //这段仅仅为了方便返回json而已
    res.header("Content-Type", "application/json;charset=utf-8");
    if(req.method == &#39;OPTIONS&#39;) {
        //让options请求快速返回
        res.sendStatus(200); 
    } else { 
        next(); 
    }
});

JAVA background configuration

##JAVA background configuration just needs to follow the following steps:

Step one: Obtain the dependent jar package

Download

cors-filter-1.7.jar, java-property-utils-1.9.jar These two libraries The file is placed in the lib directory. (Place it under webcontent/WEB-INF/lib/ of the corresponding project)

Step 2: If the project is built with Maven, please add the following dependencies to pom.xml: (If you are not Maven, please ignore it)

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>[ version ]</version>
</dependency>

The version should be the latest stable version, CORS

Filter

Step 3: Add the CORS configuration to the project's Web.xml (App/WEB- INF/web.xml)

<!-- 跨域配置-->    
<filter>
        <!-- The CORS filter with parameters -->
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
        
        <!-- Note: All parameters are options, if omitted the CORS 
             Filter will 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>
            <!--这里可以添加一些自己的暴露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 should be placed in front of web.xml as the first filter (there can be multiple filters)

Fourth Step: Possible security module configuration errors (note that some frameworks, such as company private frameworks, have security modules. Sometimes these security module configurations will affect cross-domain configuration. In this case, you can try to turn them off first)

JAVA Spring Boot Configuration##20171230 Supplement

Only list the simple global configuration

@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();        
        // 可以自行筛选
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");        
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        
        source.registerCorsConfiguration("/**", buildConfig());        
        return new CorsFilter(source);  
    }
}

New configuration, and then add Configuration annotation can be configured successfully

PS: This part of the method is included and has not been practiced personally, but based on feedback, it is theoretically feasible

NET backend configuration.NET backend configuration can refer to the following steps:

Step 1: Website configuration

Open the control panel and select management tools , select iis; right-click your website and select browse; open the directory where the website is located, use Notepad to open the web.config file and add the following configuration information, restart the website

请注意,以上截图较老,如果配置仍然出问题,可以考虑增加更多的headers允许,比如:

"Access-Control-Allow-Headers":"X-Requested-With,Content-Type,Accept,Origin"

第二步:其它更多配置,如果第一步进行了后,仍然有跨域问题,可能是:

1、接口中有限制死一些请求类型(比如写死了POST等),这时候请去除限 制

2、接口中,重复配置了Origin:*,请去除即可

3、IIS服务器中,重复配置了Origin:*,请去除即可

代理请求方式解决接口跨域问题

注意,由于接口代理是有代价的,所以这个仅是开发过程中进行的。

与前面的方法不同,前面CORS是后端解决,而这个主要是前端对接口进行代理,也就是:

1、前端ajax请求的是本地接口

2、本地接口接收到请求后向实际的接口请求数据,然后再将信息返回给前端

3、一般用node.js即可代理

关于如何实现代理,这里就不重点描述了,方法和多,也不难,基本都是基于node.js的。

搜索关键字node.js,代理请求即可找到一大票的方案。

OPTIONS预检的优化

Access-Control-Max-Age:

这个头部加上后,可以缓存此次请求的秒数。

在这个时间范围内,所有同类型的请求都将不再发送预检请求而是直接使用此次返回的头作为判断依据。

非常有用,可以大幅优化请求次数

如何分析ajax跨域

上述已经介绍了跨域的原理以及如何解决,但实际过程中,发现仍然有很多人对照着类似的文档无法解决跨域问题,主要体现在,前端人员不知道什么时候是跨域问题造成的,什么时候不是,因此这里稍微介绍下如何分析一个请求是否跨域:

抓包请求数据

第一步当然是得知道我们的ajax请求发送了什么数据,接收了什么,做到这一步并不难,也不需要fiddler等工具,仅基于Chrome即可

1、Chrome浏览器打开对应发生ajax的页面,F12打开Dev Tools

2、发送ajax请求

3、右侧面板->NetWork->XHR,然后找到刚才的ajax请求,点进去

示例一(正常的ajax请求)

The most comprehensive solution to cross-domain ajax

上述请求是一个正确的请求,为了方便,我把每一个头域的意思都表明了,我们可以清晰的看到,接口返回的响应头域中,包括了

Access-Control-Allow-Headers: X-Requested-With,Content-Type,Accept
Access-Control-Allow-Methods: Get,Post,Put,OPTIONS
Access-Control-Allow-Origin: *

所以浏览器接收到响应时,判断的是正确的请求,自然不会报错,成功的拿到了响应数据。

示例二(跨域错误的ajax请求)

为了方便,我们仍然拿上面的错误表现示例举例。

The most comprehensive solution to cross-domain ajax

这个请求中,接口Allow里面没有包括OPTIONS,所以请求出现了跨域、

The most comprehensive solution to cross-domain ajax

这个请求中,Access-Control-Allow-Origin: *出现了两次,导致了跨域配置没有正确配置,出现了错误。

更多跨域错误基本都是类似的,就是以上三样没有满足(Headers,Allow,Origin),这里不再一一赘述。

示例三(与跨域无关的ajax请求)

当然,也并不是所有的ajax请求错误都与跨域有关,所以请不要混淆,比如以下:

The most comprehensive solution to cross-domain ajax

更多

基本上都是这样去分析一个ajax请求,通过Chrome就可以知道了发送了什么数据,收到了什么数据,然后再一一比对就知道问题何在了。

总结

跨域是一个老生常谈的话题,网上也有大量跨域的资料,并且有不少精品(比如阮一峰前辈的),但是身为一个前端人员不应该浅尝而止,故而才有了本文。


The above is the detailed content of The most comprehensive solution to cross-domain ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn