Ajax - CORS - Cross Origin Resource Sharing

前端之家收集整理的这篇文章主要介绍了Ajax - CORS - Cross Origin Resource Sharing前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Below Issue only happens while trying to access some resources which are existing in a different origin

  • Issue Description
    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8089/webapp/jsp/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

  • Operations caused the issue
    Using ajax to access some other web source,like below:

<a onclick="valueAjax()">item2</a>
function valueAjax(){
  $.get("http://www.baidu.com",function (data){
             document.getElementById('a').innerHTML = data;
  }).fail(function(data) {
    alert( data);
  });
}
  • Reason analysis
    The resource which is accessing does not exist in the same origin with the requester.

  • How to resolve

    1. Simulation Environment:
      Web Server: tomcat
      Web page: jsp,html
      Script: Jquery
      a. Create html ‘page1.html’
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jquery-1.11.3.js"></script>
</head>

<body>
<div style="position: absolute; top:10px; left: 10px; border: solid 1px red; width: 100px; height: 100px" id="left">
   <button onclick="changeValue(this.innerHTML)">item1</button>
   <a onclick="valueAjax()">item2</a>
</div>
<div style="position: absolute; top:10px; left: 120px; border: solid 1px red; width: 100px; height: 100px" id="right">
   <span id="a">asf</span>
   <span>item2</span>
</div>

<script> function changeValue(val){ alert(val); document.getElementById('a').innerHTML = val; } function valueAjax(){ $.get("http://localhost:8089/webapp/jsp/login",function (data){ document.getElementById('a').innerHTML = data; }).fail(function(data) { alert( data); }); } </script>

</body>
</html>
  • Create Web project ‘webapp’,configure below filter in web.xml
<filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • Result
    Initial page -

    Succeed from ajax -

Additional knowledge
- Same-origin Policy
An origin is defined as a combination of URI scheme,hostname,and port number. If all the three parts are the same,we can say the two resources are in the same origin.
Why use it is for security concern.

Quotation
1. http://enable-cors.org/server_tomcat.html
2. http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter
3. https://en.wikipedia.org/wiki/Same-origin_policy

猜你在找的Ajax相关文章