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!

Sysprep问题可能出现在Windows11、10和8平台上。出现该问题时,Sysprep命令不会按预期运行和验证安装。如果您需要修复Sysprep问题,请查看下面的Windows11/10解决方案。Sysprep错误是如何在Windows中出现的?Sysprep无法验证您的Windows安装错误自Windows8以来一直存在。该问题通常是由于用户安装的UWP应用程序而出现的。许多用户已确认他们通过卸载从MSStore安装的某些UWP应用程序解决了此问题。如果缺少应该与Windows一起预安装

您将找到多个用户报告,确认NETHELPMSG2221错误代码。当您的帐户不再是管理员时,就会显示此信息。根据用户的说法,他们的帐户自动被撤销了管理员权限。如果您也遇到此问题,我们建议您应用指南中的解决方案并修复NETHELPMSG2221错误。您可以通过多种方式将管理员权限恢复到您的帐户。让我们直接进入它们。什么是NETHELPMSG2221错误?当您不是PC的管理员时,无法使用提升的程序。因此,例如,你将无法在电脑上运行命令提示符、WindowsPowerShell或任

什么原因导致WindowsUpdate错误0x8024800c?导致WindowsUpdate错误的原因0x8024800c尚不完全清楚。但是,此问题可能与其他更新错误具有类似的原因。以下是一些潜在的0x8024800c错误原因:损坏的系统文件–某些系统文件需要修复。不同步的软件分发缓存–软件分发数据存储不同步,这意味着此错误是超时问题(它有一个WU_E_DS_LOCKTIMEOUTEXPIRED结果字符串)。损坏的WindowsUpdate组件-错误0x8024800c是由错误的Win

MSOffice产品是任何Windows系统上用于创建Word、Excel表格等文档的应用程序的绝佳选择。但是您需要从Microsoft购买Office产品的有效许可证,并且必须激活它才能使其有效工作.最近,许多Windows用户报告说,每当他们启动任何Office产品(如Word、Excel等)时,他们都会收到一条警告消息,上面写着“您的Office许可证存在问题,并要求用户获取正版Office许可证”。一些用户不假思索,就去微软购买了Office产品的许可证

许多用户在系统变慢时报告任务管理器中存在WWAHost.exe进程。WWAHost.exe进程会占用大量系统资源,例如内存、CPU或磁盘,进而降低PC的速度。因此,每当您发现您的系统与以前相比变得缓慢时,请打开任务管理器,您会在那里找到这个WWAHost.exe进程。通常,已观察到启动任何应用程序(如Mail应用程序)会启动WWAHost.exe进程,或者它可能会自行开始执行,而无需在您的WindowsPC上进行任何外部输入。此进程是安全有效的Microsoft程序,是Wi
![如何修复iPhone上的闹钟不响[已解决]](https://img.php.cn/upload/article/000/465/014/168385668827544.png)
闹钟是当今大多数智能手机附带的良好功能之一。它不仅有助于让用户从睡眠中醒来,还可以用作在设定时间响铃的提醒。如今,许多iPhone用户抱怨iPhone上的闹钟无法正常响起,这给他们带来了问题。闹钟不响的潜在原因有很多,可能是因为iPhone处于静音模式,对闹钟设置进行了更改,选择低音调作为闹钟铃声,蓝牙设备已连接到iPhone等。在研究了此问题的各种原因后,我们在下面的帖子中编制了一组解决方案。初步解决方案确保iPhone未处于静音模式–当iPhone处于静音模式时,它只会使来自应用程序,通话和

大多数人作为备份实践将他们的文件从iPhone传输到PC/Mac,以防由于某些明显的原因而丢失。为此,他们必须通过避雷线将iPhone连接到PC/Mac。许多iPhone用户在尝试将iPhone连接到计算机以在它们之间同步文件时遇到错误1667。此错误背后有相当潜在的原因,可能是计算机或iPhone中的内部故障,闪电电缆损坏或损坏,用于同步文件的过时的iTunes应用程序,防病毒软件产生问题,不更新计算机的操作系统等。在这篇文章中,我们将向您解释如何使用以下给定的解决方案轻松有效地解决此错误。初
![修复:Windows 11 不关闭显示 [6 个简单的解决方案]](https://img.php.cn/upload/article/000/887/227/168171288789845.jpg)
Windows11可以选择在一段时间不活动后关闭显示器。当用户离开计算机并且不手动使其进入睡眠状态时,此功能可以节省电量。用户报告了即使在设置的持续时间之后他们的显示器也没有关闭的问题。幸运的是,有一些简单的解决方案可以解决这个问题。如果您的Windows11显示屏在设置时间后未关闭,则可能是由于应用程序或外部设备有问题。继续阅读本文以找到解决方案。如何调整睡眠和屏幕设置?单击开始并转到设置(或按Windows+I)。在系统下转到电源和电池。在屏幕和睡眠下,调整您希望显示器进入睡眠或关闭的时


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
