Error message :
XMLHttpRequest Cannot load http://web.image.myqcloud.com/photos/v2/10008653/bhpocket/0/?sign=4FcLKd5B8 ... P4skfvuejtz1omzt0xndq0nzexmde5jnq9mtq0ndcwnzqxoszyptezmdmymdgzotamdt0wjmy9.no ' Access-Control-Allow-Origin ' Header is present on the requested resource. Origin ' http://localhost ' is therefore not allowed access.
Analysis:
Access control allows origin to be interpreted as "access controls allow homology", which is caused by Ajax cross-domain access. The so-called cross-domain is, under the a.com domain, access to resources under the B.Com domain; For security reasons, the browser allows cross-domain write, not cross-domain read , write is upstream, send requests, send request, read is the downstream, accept the response, receive Response , understanding these two rules, we can understand the following phenomena;
1, form default submission (GET, post), hyperlink access outside the resources, this is allowed, because when the button/hyperlink is clicked, the browser address has changed, this is a normal request, there is no cross-domain;
2, Ajax (with XMLHttpRequest) cross-domain requests, this is forbidden, because Ajax is to accept the response, which violates the principle of not allowing cross-domain read
3, Jsonp is a cross-domain read and form is limited to get mode, it takes advantage of the script tag characteristics; this is allowed. Because the browser treats cross-domain read scripts as an exception, SRC of similar img, IFRAME can request an extraterritorial resource
Solution:
Scenario 1, add parameter,--to Chrome browser disable-web-security
Scenario 2
A
Non-IE browser, using XMLHttpRequest, add origin to the request header: This domain name address, usually do not need to add manually, the browser will move to add
ie, using xdomainrequest to send a request, it will automatically encapsulate the header to add Origin
B,response Header Add access-control-allow-origin:*
Cross-domain demos and code
The verification process first accesses http://Native ip:port/project_name/a.jsp, then a.jsp sends an AJAX request http://localhost:port/project_name/b.jsp, which creates a cross-domain problem.
a.jsp
[HTML]View PlainCopy
- <%@ page language="java" contenttype="text/html; Charset=utf-8 "
- pageencoding="UTF-8"%>
- <html xmlns= "http://www.w3.org/1999/xhtml" dir="ltr">
- <head>
- <Meta http-equiv= "content-type" content= "text/html; Charset=utf-8 "/>
- <title> Cross-domain demo </title>
- <script type="Text/javascript" src="Jquery-1.11.2.js"></Script >
- <script type="Text/javascript" src="Jquery.form.js"></script>
- </head>
- <script type="Text/javascript">
- $ (document). Ready (function () {
- $.getjson (' http://localhost/test_maven/b.jsp ', function (data) {
- Alert ("Request Succeed");
- });
- });
- </Script>
- </body>
b.jsp
[HTML]View PlainCopy
- <%@ page language="java" contenttype="text/html; Charset=utf-8 "
- pageencoding="UTF-8"%>
- <%
- Response.setheader ("Access-control-allow-origin", "*");
- Response.getwriter (). Write ("Hahahhaha");
- %>
If you comment out the Response.setheader ("Access-control-allow-origin", "*"), then the access Control allow Origin error, using the wildcard character *, All cross-domain access is allowed, so cross-domain access is successful .
However, it is dangerous to use wildcards *, which allows cross-domain request access from any domain, so it is often more precise to control in a production environment;
Simple request
The above request is a simple request, as long as the addition of access-control-allow-origin:*, will be access to success, if it is a complex request, we need to further processing to succeed. Here's an explanation of what simple and complex requests are.
[HTML]View PlainCopy
- Simple requests
- A Simple Cross-site request is one, meets all the following conditions:
- The only allowed methods is:
- GET
- HEAD
- POST
- Apart from the headers set automatically by the user agent (e.g. Connection, user-agent, etc.), the only headers which is Allowed to be manually set is:
- Accept
- Accept-language
- Content-language
- Content-type
- The only allowed values for the Content-type header is:
- application/x-www-form-urlencoded
- Multipart/form-data
- Text/plain
Simply put, these are " simple requests ", except for simple requests, which are " complex requests ".
Complex requests
Before the official post, the browser makes an options request (also called preflight), with the header with Origin and access-control-request-*:* * , The server response will return the appropriate access-control-allow-origin, and if so, the browser will send a formal post, otherwise the above error will occur. This also answers the question of when cross-domain access, when we send a POST request, fails to see what Chrome network will find to be the options method.
According to the above procedure, the background method needs the options method, the following is the test sample.
The content-type here do not belong to any of the (Application/x-www-form-urlencoded,multipart/form-data,text/plain), so it is a complex request.
[HTML]View PlainCopy
- $.ajax ({
- Type: "Post",
- URL: "Http://localhost/test_maven/a_action",
- ContentType: "Application/json",
- DataType: "JSON",
- Success:function () {
- Alert ("Request Succeed");
- }
- });
[HTML]View PlainCopy
- @RequestMapping (value = "/a_action",
- method=requestmethod.options)
- public void Aactionoption (HttpServletResponse response) throws ioexception{
- SYSTEM.OUT.PRINTLN ("option execute ...");
- Response.setheader ("Access-control-allow-headers", "Accept, Content-type");
- Response.setheader ("Access-control-allow-method", "POST");
- Response.setheader ("Access-control-allow-origin", "http://192.168.8.36");
- }
[HTML]View PlainCopy
- @RequestMapping (value = "/a_action",method=requestmethod.post)
- public void Aaction (HttpServletResponse response) throws ioexception{
- System.out.println ("A_action execute ...");
- }
The first is the options request, the HTTP options request, like get, post, head, and so on, are the HTTP request method, the options method, to obtain a server-side URL support method, response Methods supported by the Allow flag in the header
The second time is the real request.
This scenario is based on the latest specification of the Web, so the program relies on browser implementations.
Summarize:
The access control Allow Origin error indicates that the cross-domain request failed! The browser sends the request successfully, the browser also receives the response, but restricts the xmlhttprquest to receive the request, will not let the XMLHttpRequest accept the response, and error in the JS console. This is why we can see that the HTTP status code is 200 in the network console, but JS error occurs in the JS console.
Original Blog Address: http://blog.csdn.net/wangjun5159/article/details/49096445
Related Questions Blog: http://www.tangshuang.net/2271.html (explains when a simple request is a complex request.) )
The options request in Ajax is also a case of early detection, when the Ajax cross-domain request, if the request is JSON, is a complex request, so need to issue an options request in advance to check whether the request is reliable and secure, If the options get responses that are rejected, such as HTTP status such as 404\403\500, the issue of the post, put, and other requests will be stopped.
Access control allow Origin simple requests and complex requests