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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值