目录
1.什么叫做跨域请求
跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据。只要协议、域名、端口有任何一个不同,都被当作是不同的域。
2.跨域调用测试
(1)启动一个服务,端口号为8080
@RestController
public class CORSController {
@RequestMapping("findName")
public Map findName() {
Map map = new HashMap();
map.put("name", "张三");
map.put("age", 18);
return map;
}
}
(2)启动另一个服务,端口号为9090
test.html
<script src="js/angular.js"></script>
<script>
var app=angular.module("myApp",[]);
app.controller("myController",function ($http,$scope) {
$scope.findName=function () {
$http.get('http://localhost:8080/findName.do').success(
function (response) {
$scope.person=response;
}
)
}
})
</script>
<body ng-app="myApp" ng-controller="myController" ng-init="findName()">
{{person.name}}<br/>
{{person.age}}
当9090的服务调用8080的findName方法时,会报如下的错误

Failed to load http://localhost:8080/findName.do: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9090' is therefore not allowed access. The response had HTTP status code 404.
3.解决方案CORS跨域
(1)概述
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。
它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。
(2)请求过程
请求过程如下图:

Preflight Request:

然后服务器端给我们返回一个Preflight Response

(3)解决办法
Access-Control-Allow-Origin
Access-Control-Allow-Origin是HTML5中定义的一种解决资源跨域的策略。
他是通过服务器端返回带有Access-Control-Allow-Origin标识的Response header,用来解决资源的跨域权限问题。
使用方法,在response添加 Access-Control-Allow-Origin,例如
Access-Control-Allow-Origin:www.google.com
也可以设置为 * 表示该资源谁都可以用
更改8080端口的controller方法
@RestController
public class CORSController {
@RequestMapping("findName")
public Map findName(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:9090");
Map map = new HashMap();
map.put("name", "张三");
map.put("age", 18);
return map;
}
}
重新访问http://localhost:9090/test.html,可以跨域请求成功
如果要操作cookie,后端controller层加如下代码
response.setHeader("Access-Control-Allow-Origin", "http://localhost:9090");
//此时Access-Control-Allow-Origin无法用*匹配任意地址,必须指定精确的路径
response.setHeader("Access-Control-Allow-Credentials", "true");
前端必须在AJAX请求中打开withCredentials属性
$http.get('http://localhost:8080/cors01/findName.do',{'withCredentials':true})
请求头如下:

响应头如下:

(4)SpringMVC跨域注解
springMVC的版本在4.2或以上版本,可以使用注解实现跨域, 我们只需要在需要跨域的方法上添加注解@CrossOrigin即可
@CrossOrigin(origins="http://localhost:9090",allowCredentials="true")
allowCredentials="true" 可以缺省
2500

被折叠的 条评论
为什么被折叠?



