跨域产生原因及处理方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013219624/article/details/84573422

1.跨域产生原因

当前站点页面访问当前站点之外的资源

2.产生跨域例子(直接浏览器打开 访问localhost:8080的资源)

<!DOCTYPE html>
<html>
<head>
<title>跨域</title>
<script src="jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $.ajax({
        url:'http://localhost:8080/test01',
        type : 'get',
        dataType : 'text',
        success:function(data){
            console.log(data);
        },
        error:function(data){
            console.log("error.");
        }        
    });
</script>
</head>
<body>
</body>
</html>

3.处理方式一

@RequestMapping("/test01")
@ResponseBody
public User test01(HttpServletResponse response) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    return new User("test01", 10);
}

4.处理方式二

@RequestMapping("/test01")
@ResponseBody
@CrossOrigin
public User test01() {
    return new User("test01", 10);
}

猜你喜欢

转载自blog.csdn.net/u013219624/article/details/84573422
今日推荐