Access control allow Origin simple requests and complex requests

Source: Internet
Author: User
Tags script tag


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 
  1. <%@ page language="java" contenttype="text/html; Charset=utf-8 "
  2. pageencoding="UTF-8"%>
  3. <html xmlns= "http://www.w3.org/1999/xhtml" dir="ltr">
  4. <head>
  5. <Meta http-equiv= "content-type" content= "text/html; Charset=utf-8 "/>
  6. <title> Cross-domain demo </title>
  7. <script type="Text/javascript" src="Jquery-1.11.2.js"></Script >
  8. <script type="Text/javascript" src="Jquery.form.js"></script>
  9. </head>
  10. <script type="Text/javascript">
  11. $ (document). Ready (function () {
  12. $.getjson (' http://localhost/test_maven/b.jsp ', function (data) {
  13. Alert ("Request Succeed");
  14. });
  15. });
  16. </Script>
  17. </body>

b.jsp

[HTML]View PlainCopy  
    1. <%@ page language="java" contenttype="text/html; Charset=utf-8 "
    2. pageencoding="UTF-8"%>
    3. <%
    4. Response.setheader ("Access-control-allow-origin", "*");
    5. Response.getwriter (). Write ("Hahahhaha");
    6. %>

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 
  1. Simple requests
  2. A Simple Cross-site request is one, meets all the following conditions:
  3. The only allowed methods is:
  4. GET
  5. HEAD
  6. POST
  7. 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:
  8. Accept
  9. Accept-language
  10. Content-language
  11. Content-type
  12. The only allowed values for the Content-type header is:
  13. application/x-www-form-urlencoded
  14. Multipart/form-data
  15. 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 
  1. $.ajax ({
  2. Type: "Post",
  3. URL: "Http://localhost/test_maven/a_action",
  4. ContentType: "Application/json",
  5. DataType: "JSON",
  6. Success:function () {
  7. Alert ("Request Succeed");
  8. }
  9. });



[HTML]View PlainCopy 
  1. @RequestMapping (value = "/a_action",
  2. method=requestmethod.options)
  3. public void Aactionoption (HttpServletResponse response) throws ioexception{
  4. SYSTEM.OUT.PRINTLN ("option execute ...");
  5. Response.setheader ("Access-control-allow-headers", "Accept, Content-type");
  6. Response.setheader ("Access-control-allow-method", "POST");
  7. Response.setheader ("Access-control-allow-origin", "http://192.168.8.36");
  8. }

[HTML]View PlainCopy 
    1. @RequestMapping (value = "/a_action",method=requestmethod.post)
    2. public void Aaction (HttpServletResponse response) throws ioexception{
    3. System.out.println ("A_action execute ...");
    4. }


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.