Origin
Non-homologous cannot be requested due to the browser's homologous policy.
However, in practice, there are often situations that require cross-domain requests for resources, and more typically applications such as a subdomain to request user information from a subdomain that is responsible for user authentication.
Previously, cross-domain access could be achieved through JSONP, Flash, or server relay, but now we have cors.
Compared with JSONP, Cors is undoubtedly more advanced, convenient and reliable.
| 123 |
1、 JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。2、 使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更好的错误处理。3、 JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS |
The most basic principle of JSONP
Add a <script> tag dynamically, and the SRC attribute of the script tag is not a cross-domain limitation. In this way, this cross-domain approach is actually unrelated to the Ajax XMLHttpRequest protocol.
In fact, "jquery Ajax cross-domain problem" has become a pseudo-proposition, jquery $.ajax method name is misleading.
If set to datatype: ' Jsonp ', this $.ajax method has nothing to do with Ajax XMLHttpRequest, instead it is the JSONP protocol. JSONP is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access through JavaScript callback.
JSONP is the JSON with Padding. Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If cross-domain requests are made, we can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where the JavaScript object can be passed directly using JSON. This cross-domain communication method is called JSONP.
Cross-origin Resource Sharing
This is a new standard, the simple is to use the server/client some headers settings and confirmation to achieve cross-domain requests, these headers have
Cross-origin Resource Sharing
This is a new standard, the simple is to use the server/client some headers settings and confirmation to achieve cross-domain requests, these headers have
Syntax
- 5.1
Access-Control-Allow-Origin Response Header
- 5.2
Access-Control-Allow-Credentials Response Header
- 5.3
Access-Control-Expose-Headers Response Header
- 5.4
Access-Control-Max-Age Response Header
- 5.5
Access-Control-Allow-Methods Response Header
- 5.6
Access-Control-Allow-Headers Response Header
- 5.7
Origin Request Header
- 5.8
Access-Control-Request-Method Request Header
- 5.9
Access-Control-Request-Headers Request Header
For example
- Access-control-allow-origin:http://www.test.com
- Access-control-allow-methods:post, GET, OPTIONS
- Access-control-allow-headers:powered-by-mengxianhui
- Access-control-max-age:30
You can refer to http://www.w3.org/TR/access-control/#access-control-allow-origin-response-header website
| 1234567 |
Access-Control-Allow-Origin: 允许跨域访问的域,可以是一个域的列表,也可以是通配符"*"。这里要注意Origin规则只对域名有效,并不会对子目录有效。即http://www.test/test/是无效的。但是不同子域名需要分开设置,这里的规则可以参照那篇同源策略Access-Control-Allow-Credentials: 是否允许请求带有验证信息,这部分将会在下面详细解释Access-Control-Expose-Headers: 允许脚本访问的返回头,请求成功后,脚本可以在XMLHttpRequest中访问这些头的信息(貌似webkit没有实现这个)Access-Control-Max-Age: 缓存此次请求的秒数。在这个时间范围内,所有同类型的请求都将不再发送预检请求而是直接使用此次返回的头作为判断依据,非常有用,大幅优化请求次数Access-Control-Allow-Methods: 允许使用的请求方法,以逗号隔开Access-Control-Allow-Headers: 允许自定义的头部,以逗号隔开,大小写不敏感 |
Access-control-allow-credentials
In cross-domain requests, by default, the HTTP authentication information, the cookie header, and the user's SSL certificate are not sent either in the preflight request or in the actual request.
However, by setting XMLHttpRequest credentials to true, the authentication information mechanism is enabled.
Although a simple request does not require a preflight request to be sent, it is now necessary to determine whether the request is successful or not, and if Access-control-allow-credentials is false, the Access-control-allow-credentials The request failed.
It is very important to note that at this time Access-control-allow-origin can not be a wildcard "*" (really cheap a bunch of lazy programmers), if Access-control-allow-origin is a wildcard "*", The request will still be considered failed
Even if the request is unsuccessful, the browser will set the cookie as usual if the Set-cookie header is returned.
Client Page test.php
| 1234567891011121314151617181920212223242526272829 |
<!DOCTYPE html>"http://www.w3.org/1999/xhtml"> <title>crossDomainRequest</title> <body> <input type=‘button‘value=‘开始测试‘onclick="crossDomainRequest()"/> <div id="content"></div> <script type="text/javascript">functioncreateXHR(){ returnwindow.XMLHttpRequest? newXMLHttpRequest(): newActiveXObject("Microsoft.XMLHTTP");}functiongetappkey(url){ xmlHttp = createXHR(); xmlHttp.open("GET",url,false); xmlHttp.send(); result = xmlHttp.responseText; returnresult;}functioncrossDomainRequest(){ var content =getappkey(‘http://127.0.0.10/gettest.php‘); document.getElementById("content").innerHTML=content;}</script> </body> |
Service-side page gettest.php
| 1234 |
<?phpheader("Access-Control-Allow-Origin: http://127.0.0.1");echo"test success!";?> |
If it's not allowed.
So there are several ways to cross the domain
cross-domain with webserver "nginx" Configuration
| 123456789101112131415161718192021222324252627282930313233343536 |
## Wide-open CORS config for nginx#location / { if($request_method = ‘OPTIONS‘) { add_header ‘Access-Control-Allow-Origin‘‘*‘; # # Om nom nom cookies # add_header ‘Access-Control-Allow-Credentials‘‘true‘; add_header ‘Access-Control-Allow-Methods‘‘GET, POST, OPTIONS‘; # # Custom headers and headers various browsers *should* be OK with but aren‘t # add_header ‘Access-Control-Allow-Headers‘‘DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type‘; # # Tell client that this pre-flight info is valid for 20 days # add_header ‘Access-Control-Max-Age‘1728000; add_header ‘Content-Type‘‘text/plain charset=UTF-8‘; add_header ‘Content-Length‘0; return204; } if ($request_method = ‘POST‘) { add_header ‘Access-Control-Allow-Origin‘‘*‘; add_header ‘Access-Control-Allow-Credentials‘‘true‘; add_header ‘Access-Control-Allow-Methods‘‘GET, POST, OPTIONS‘; add_header ‘Access-Control-Allow-Headers‘‘DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type‘; } if($request_method = ‘GET‘) { add_header ‘Access-Control-Allow-Origin‘‘*‘; add_header ‘Access-Control-Allow-Credentials‘ ‘true‘; add_header ‘Access-Control-Allow-Methods‘‘GET, POST, OPTIONS‘; add_header ‘Access-Control-Allow-Headers‘‘DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type‘; }} |
Sample code
| 12345678910 |
location /{add_header ‘Access-Control-Allow-Origin‘‘http://www.test.com‘;add_header ‘Access-Control-Allow-Credentials‘ ‘true‘;add_header ‘Access-Control-Allow-Methods‘ ‘GET‘; ...... } |
First instruction: authorizing requests from http://www.test.com
Second instruction: When the flag is true, responds to whether the request can be exposed
The third day directive: Specifies the method of the request, which can be get,post, etc.
If you need to allow access from any domain, you can configure this
| 1 |
Access-Control-Allow-Origin: * |
cross-domain through a backend program
| 1234567891011121314151617181920 |
<?phpheader("Access-Control-Allow-Origin:http://www.test.com");header("Access-Control-Allow-Origin:*");echojson_encode($_POST);?><script type="text/javascript">$("#ajax").click(function(){ $.ajax({ type: "POST", url: "http://www.test.com/test2.php", data: ‘name=test‘, dataType:"json", success: function(data){ $(‘#Result‘).text(data.name); } });});</script> |
JSONP
| 1234567891011121314151617181920212223242526 |
<?phpif(isset($_GET[‘name‘]) && isset($_GET[‘callback‘])) //callback根js端要对应,不然会报错的{ echo$_GET[‘callback‘]. ‘(‘. json_encode($_GET) . ‘);}?><script type="text/javascript">$("#jsonp").click(function(){ $.ajax({ url: ‘http://www.test.com/test1.php‘, data: {name: ‘jsonp‘}, dataType: ‘jsonp‘, jsonp: ‘callback‘, //为服务端准备的参数 jsonpCallback: ‘getdata‘, //回调函数 success: function(){ alert("success"); } });});functiongetdata(data){ $(‘#Result‘).text(data.name);}</script> |
Getjson
| 12345678 |
<script type="text/javascript">$("#getjson").click(function(){ $.getJSON(‘http://www.test.com/test1.php?name=getjson&callback=?‘, function(data){ //没有回调函数,直接处理 $(‘#Result‘).text(data.name); })})</script> |
GetScript
| 12345 |
<script type="text/javascript">$("#getscript").click(function(){ $.getScript(‘http://www.test.com/test1.php?name=getscript&callback=getdata‘);});</script> |
Cross-domain requests for XMLHttpRequest