跨域请求问题解决
什么叫做跨域请求
- 跨域是指 请求的协议/端口号/域名 任何一个不同都可以被称为跨域请求,例如 ajax 异步向不同的域请求数据,又或者 js 获取页面中不同域的框架中(iframe)的数据。分布式项目中应用更加广泛
跨域请求的报错内容
测试后发现无法跨域调用
XMLHttpRequest cannot load
No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin
‘http://localhost:9100’ is therefore not allowed access. The response had HTTP status code 400.
跨域解决方案 CORS
- CORS 是一个 W3C 标准,全称是”跨域资源共享”(Cross-origin resource sharing),目前所有浏览器都支持该功能。
原理图
抓包截图
代码示例
客户端请求的URL
$http.get('http://localhost:9105/file.do?num='$scope.num',{'withCredentials':true})
.success(
function(response){
.......
}
);
需要在服务端配置代码
HttpServletResponse response = new HttpServletResponse();
//1. 也可以设置 "http://localhost:9109" 为* 代表任何路径都可以访问
//2. Access-Control-Allow-Origin 是 HTML5 中定义的一种解决资源跨域的策略
response.setHeader("Access-Control-Allow-Origin", "http://localhost:9109");
//3. 如果要发送cookie信息 需要添加下面的响应头,而且同时要请求客户端 添加{'withCredentials':true})属性
response.setHeader("Access-Control-Allow-Credentials", "true");
SpringMVC 跨域请求注解
springMVC 的版本在 4.2 或以上版本,可以使用注解实现跨域, 我们只需要在需要跨域的方
法上添加注解@CrossOrigin 即可其实就是上面两步的注解方式
@CrossOrigin(origins=”http://localhost:9109”,allowCredentials=”true”)
来源:CSDN
作者:刘广睿
链接:https://blog.csdn.net/a18302465887/article/details/78236278