This article will share with you the most complete ajax cross-domain solution. Ever since I first came into contact with front-end development, the word <span style="font-size: 14px;">cross-domain</span>
has always been It reappears around me with a very high frequency. Until now, I have debugged N cross-domain related issues. I also compiled a related article in 2016, but I still feel that something is missing, so I have reorganized it now. one time.
Question outline
Regarding cross-domain, there are N types. This article only focuses on <span style="font-size: 14px;">ajax requests Cross-domain </span>
(, Ajax cross-domain is only part of the browser's "same-origin policy", others include Cookie cross-domain, iframe cross-domain, LocalStorage cross-domain, etc., which will not be introduced here), The content is roughly as follows:
What is ajax cross-domain
Principle
Performance (organized some problems encountered and solutions)
How to solve ajax cross-domain
JSONP way
CORS way
Proxy request method
How to analyze ajax cross-domain
http packet capture analysis
Some examples
What is ajax cross-domain
The principle of ajax cross-domain
ajax request appears The main reason for the cross-domain error problem is the browser's "same origin policy". You can refer to
Browser Same Origin Policy and How to Avoid It (Ruan Yifeng)
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, thus 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. However, front-end developers may not usually Just concerned (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 (Ruan Yifeng)
In addition, here is also a summary Implementation schematic diagram (simplified version):
##How to judge whether it is a simple request?<span style="font-size: 14px;"></span>
Browsers divide CORS requests into two categories: simple requests and not-so-simple requests. As long as the following two conditions are met at the same time, it is a simple request. <span style="font-size: 14px;"></span>
The request method is one of the following three methods: HEAD, GET, POST<span style="font-size: 14px;"></span>
HTTP header information does not exceed the following fields: <span style="font-size: 14px;"></span>
Accept<span style="font-size: 14px;"></span>
Accept-Language<span style="font-size: 14px;"></span>
- ##Content-Language
<span style="font-size: 14px;"></span>
##Last-Event-ID <span style="font-size: 14px;"></span>
Content-Type (limited to three values application/x-www-form-urlencoded, multipart/form-data, text/plain)<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"></span>Ajax cross-domain performance
<span style="font-size: 14px;"></span>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:<span style="font-size: 14px;">No 'Access-Control-Allow-Origin' header is present on the requested resource</span>
, and<span style="font-size: 14px;">The response had HTTP status code 404</span>
## The reasons for this situation are as follows: <span style="font-size: 14px;"></span>
This ajax request is a "non-simple request", so a preflight request (OPTIONS) will be sent before the request<span style="font-size: 14px;"></span>
The server-side background interface does not allow OPTIONS requests, resulting in the inability to find the corresponding interface address<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"></span>
Second phenomenon:
<span style="font-size: 14px;"></span>No 'Access-Control-Allow-Origin' header is present on the requested resource<span style="font-size: 14px;"></span>, and
<span style="font-size: 14px;"></span>The response had HTTP status code 405<span style="font-size: 14px;"></span>
Security Configuration <span style="font-size: 14px;"></span>), blocking the OPTIONS request will cause this phenomenon
<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"></span>
The third phenomenon:
<span style="font-size: 14px;"></span>No 'Access-Control-Allow-Origin' header is present on the requested resource<span style="font-size: 14px;"></span>, and
status 200<span style="font-size: 14px;"></span>
##This phenomenon is different from the first and second ones. In this case, the server-side background allows OPTIONS requests, and the interface also allows OPTIONS requests, but there is a mismatch when the header matches.
<span style="font-size: 14px;"></span>For example, the origin header check does not match, for example, it is missing Support for some headers (such as the common X-Requested-With header), 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
<span style="font-size: 14px;"></span>Solution: Add corresponding header support to the backend
<span style="font-size: 14px;"></span>Fourth phenomenon:
heade contains multiple values '* ,*'<span style="font-size: 14px;"></span>
##phenomenon Yes, the background response http header information has two
Access-Control-Allow-Origin:*<span style="font-size: 14px;"></span><span style="font-size: 14px;"></span>To be honest, this kind of The main reason for the problem is that people who perform cross-domain configuration do not understand the principles, resulting in repeated configurations, such as:
<span style="font-size: 14px;"></span>
is common in the .net background (generally in the web The origin is configured once in .config, and then the origin is manually added to the code (for example, the code manually sets the return *))-
<span style="font-size: 14px;"></span>
commonly found in the .net backend (Set Origin:* in both IIS and the project's webconfig) -
<span style="font-size: 14px;"></span>
Solution (one-to-one correspondence):
<span style="font-size: 14px;"></span>
It is recommended to delete the manually added * in the code and only use the ones in the project configuration-
<span style="font-size: 14px;"></span>
It is recommended to delete the configuration* under IIS , just use the ones in the project configuration
How to solve ajax cross-domain
Generally, ajax cross-domain solution is solved through JSONP or CORS, as follows: (Note, now it has been solved I almost never use JSONP anymore, so just understand JSONP)
JSONP way to solve cross-domain problems
jsonp solves cross-domain problems It is a relatively old solution (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 solutions is mainly because <script> scripts have cross-domain capabilities, and JSONP uses To achieve this. The specific principle is shown in the figure </script>
Implementation process
The implementation steps of JSONP are roughly As follows (referring to the article in the source)
-
The client web page requests JSON data from the server by adding a <script> element. This approach does not allow Restricted by the same-origin policy</script>
<span style="font-size: 14px;">function addScriptTag(src) {<br> var script = document.createElement('script');<br> script.setAttribute("type","text/javascript");<br> script.src = src;<br> document.body.appendChild(script);<br>}<br><br>window.onload = function () {<br> addScriptTag('http://example.com/ip?callback=foo');<br>}<br><br>function foo(data) {<br> console.log('response data: ' + JSON.stringify(data));<br>}; <br> <br></span>
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
The corresponding interface on the server side adds a function wrapping layer outside the return parameter
<span style="font-size: 14px;">foo({<br> "test": "testData"<br>}); <br></span>
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 parameters are treated as 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, so if the interface is to be JSONO compatible, it needs to be judged whether there is a corresponding callback key Word parameters, if any, it is a JSONP request, returning JSONP data, otherwise returning ordinary data
Notes on use
Based on the implementation principle of JSONP, JSONP can only be used for "GET" requests and cannot perform more complex POST and other requests. So when encountering that situation, you have to refer to the following CORS to solve cross-domain issues (so now it is basically used Eliminated)
CORS solves cross-domain problems
The principle of CORS has been introduced above. What is mainly introduced here is that in actual projects , how the backend should be configured to solve the problem (because a large number of project practices are solved by the backend), here are some common backend solutions:
PHP background configuration
The configuration of the PHP backend is almost the simplest of all backends. Just follow the following steps:
Step one: Configure the Php backend to allow cross-domain
<span style="font-size: 14px;"><?php <br/>header('Access-Control-Allow-Origin: *');<br>header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');<br>//主要为跨域CORS配置的两大基本信息,Origin和headers<br></span>
Step two: Configure the Apache web server for cross-domain (in httpd.conf)
Original code
<span style="font-size: 14px;"><directory></directory><br> AllowOverride none<br> Require all denied<br><br></span>
Change to the following code
<span style="font-size: 14px;"><directory></directory><br> Options FollowSymLinks<br> AllowOverride none<br> Order deny,allow<br> Allow from all<br><br></span>
Node.js background configuration (express framework)
The background of Node.js is relatively simple and can be configured. Just use express to configure as follows:
<span style="font-size: 14px;">app.all('*', function(req, res, next) {<br> res.header("Access-Control-Allow-Origin", "*");<br> res.header("Access-Control-Allow-Headers", "X-Requested-With");<br> res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");<br> res.header("X-Powered-By", ' 3.2.1')<br> //这段仅仅为了方便返回json而已<br> res.header("Content-Type", "application/json;charset=utf-8");<br> if(req.method == 'OPTIONS') {<br> //让options请求快速返回<br> res.sendStatus(200); <br> } else { <br> next(); <br> }<br>});<br></span>
JAVA background configuration
##JAVA background configuration just needs to follow the following steps:<span style="font-size: 14px;"></span>
-
Step one: Obtain the dependent jar package<span style="font-size: 14px;"></span>
Download cors-filter-1.7.jar, java-property-utils-1.9 .jar These two library files are placed in the lib directory. (Place it under webcontent/WEB-INF/lib/ of the corresponding project)<span style="font-size: 14px;"></span>
Step 2: If the project is built with Maven, please add the following dependencies Go to pom.xml: (please ignore if you are not maven)<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"><dependency><br> <groupid>com.thetransactioncompany</groupid><br> <artifactid>cors-filter</artifactid><br> <version>[ version ]</version><br></dependency><br></span>
The version should be the latest stable version, CORS filter<span style="font-size: 14px;"></span>
Step 3: Add CORS configuration to the project's Web.xml (App/WEB-INF/web.xml)<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"><!-- 跨域配置--> <br><filter><br> <!-- The CORS filter with parameters --><br> <filter-name>CORS</filter-name><br> <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class><br> <br> <!-- Note: All parameters are options, if omitted the CORS <br/> Filter will fall back to the respective default values.<br/> --><br> <init-param><br> <param-name>cors.allowGenericHttpRequests</param-name><br> <param-value>true</param-value><br> </init-param><br> <br> <init-param><br> <param-name>cors.allowOrigin</param-name><br> <param-value>*</param-value><br> </init-param><br> <br> <init-param><br> <param-name>cors.allowSubdomains</param-name><br> <param-value>false</param-value><br> </init-param><br> <br> <init-param><br> <param-name>cors.supportedMethods</param-name><br> <param-value>GET, HEAD, POST, OPTIONS</param-value><br> </init-param><br> <br> <init-param><br> <param-name>cors.supportedHeaders</param-name><br> <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value><br> </init-param><br> <br> <init-param><br> <param-name>cors.exposedHeaders</param-name><br> <!--这里可以添加一些自己的暴露Headers --><br> <param-value>X-Test-1, X-Test-2</param-value><br> </init-param><br> <br> <init-param><br> <param-name>cors.supportsCredentials</param-name><br> <param-value>true</param-value><br> </init-param><br> <br> <init-param><br> <param-name>cors.maxAge</param-name><br> <param-value>3600</param-value><br> </init-param><br><br> </filter><br><br> <filter-mapping><br> <!-- CORS Filter mapping --><br> <filter-name>CORS</filter-name><br> <url-pattern>/*</url-pattern><br> </filter-mapping><br></span>
Please note that the above configuration file should be placed in front of web.xml and exist as the first filter (there can be multiple filters)<span style="font-size: 14px;"></span>
第四步:可能的安全模块配置错误(注意,某些框架中-譬如公司私人框架,有安全模块的,有时候这些安全模块配置会影响跨域配置,这时候可以先尝试关闭它们)
NET后台配置
.NET后台配置可以参考如下步骤:
第一步:网站配置
打开控制面板,选择管理工具,选择iis;右键单击自己的网站,选择浏览;打开网站所在目录,用记事本打开web.config文件添加下述配置信息,重启网站
请注意,以上截图较老,如果配置仍然出问题,可以考虑增加更多的headers允许,比如:
<span style="font-size: 14px;">"Access-Control-Allow-Headers":"X-Requested-With,Content-Type,Accept,Origin" <br></span>
第二步:其它更多配置,如果第一步进行了后,仍然有跨域问题,可能是:
接口中有限制死一些请求类型(比如写死了POST等),这时候请去除限 制
接口中,重复配置了
<span style="font-size: 14px;">Origin:*</span>
,请去除即可IIS服务器中,重复配置了
<span style="font-size: 14px;">Origin:*</span>
,请去除即可
代理请求方式解决接口跨域问题
注意,由于接口代理是有代价的,所以这个仅是开发过程中进行的。
与前面的方法不同,前面CORS是后端解决,而这个主要是前端对接口进行代理,也就是:
前端ajax请求的是本地接口
本地接口接收到请求后向实际的接口请求数据,然后再将信息返回给前端
一般用node.js即可代理
关于如何实现代理,这里就不重点描述了,方法和多,也不难,基本都是基于node.js的。
搜索关键字<span style="font-size: 14px;">node.js</span>
,<span style="font-size: 14px;">代理请求</span>
即可找到一大票的方案。
如何分析ajax跨域
上述已经介绍了跨域的原理以及如何解决,但实际过程中,发现仍然有很多人对照着类似的文档无法解决跨域问题,主要体现在,前端人员不知道什么时候是跨域问题造成的,什么时候不是,因此这里稍微介绍下如何分析一个请求是否跨域:
抓包请求数据
第一步当然是得知道我们的ajax请求发送了什么数据,接收了什么,做到这一步并不难,也不需要<span style="font-size: 14px;">fiddler</span>
等工具,仅基于<span style="font-size: 14px;">Chrome</span>
即可
<span style="font-size: 14px;">Chrome</span>
浏览器打开对应发生ajax的页面,<span style="font-size: 14px;">F12</span>
打开<span style="font-size: 14px;">Dev Tools</span>
发送ajax请求
右侧面板->
<span style="font-size: 14px;">NetWork</span>
-><span style="font-size: 14px;">XHR</span>
,然后找到刚才的ajax请求,点进去
示例一(正常的ajax请求)
上述请求是一个正确的请求,为了方便,我把每一个头域的意思都表明了,我们可以清晰的看到,接口返回的响应头域中,包括了
<span style="font-size: 14px;">Access-Control-Allow-Headers: X-Requested-With,Content-Type,Accept<br>Access-Control-Allow-Methods: Get,Post,Put,OPTIONS<br>Access-Control-Allow-Origin: *<br></span>
所以浏览器接收到响应时,判断的是正确的请求,自然不会报错,成功的拿到了响应数据。
示例二(跨域错误的ajax请求)
为了方便,我们仍然拿上面的错误表现示例举例。
这个请求中,接口Allow里面没有包括<span style="font-size: 14px;">OPTIONS</span>
,所以请求出现了跨域、
这个请求中,<span style="font-size: 14px;">Access-Control-Allow-Origin: *</span>
出现了两次,导致了跨域配置没有正确配置,出现了错误。
更多跨域错误基本都是类似的,就是以上三样没有满足(Headers,Allow,Origin),这里不再一一赘述。
示例三(与跨域无关的ajax请求)
当然,也并不是所有的ajax请求错误都与跨域有关,所以请不要混淆,比如以下:
比如这个请求,它的跨域配置没有一点问题,它出错仅仅是因为request的<span style="font-size: 14px;">Accept</span>
和response的<span style="font-size: 14px;">Content-Type</span>
不匹配而已。
更多
基本上都是这样去分析一个ajax请求,通过<span style="font-size: 14px;">Chrome</span>
就可以知道了发送了什么数据,收到了什么数据,然后再一一比对就知道问题何在了。
写在最后的话
跨域是一个老生常谈的话题,网上也有大量跨域的资料,并且有不少精品(比如阮一峰前辈的),但是身为一个前端人员不应该浅尝而止,故而才有了本文。
漫漫前端路,望与诸君共勉之!
相关推荐:
The above is the detailed content of The most complete ajax cross-domain solution. For more information, please follow other related articles on the PHP Chinese website!

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
