跨域

同源策略

浏览器采用了同源策略,只有位于相同域中的其它页面才访问这些数据。

1、协议:协议必须匹配。如果在以httpd起始的页面上保存了数据,那么此数据就无法通过https来访问。

2、子域名:子域名必须匹配。例如maps.google.com无法访问www.google.com上存储的数据。

3、域名:域名必须匹配。如例如google不能访问baidu.com上存储的数据。

4、端口号:端口号必须匹配。web服务器可以指定各种端口号。URL中通常不指定端口号,默认使用80端口。

跨来源资源共享

与同源策略相反的是跨来源资源共享。

跨来源资源共享(CORS),亦译为跨域资源共享,是一份浏览器技术的规范,提供了 Web 服务从不同网域传来沙盒脚本的方法,以避开浏览器的同源策略。

来用跨来源资源共享可以解决同源策略产生的问题。

主要从两个方面来解决:一是服务端,二是客户端。

服务端有servlet jersey spring,分别有不同的解决方案。

servlet在过滤中添加以下代码

1
2
3
4
5
6
7
8
9
10
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
         throws IOException, ServletException {
 
     HttpServletRequest request = (HttpServletRequest) servletRequest;
 
     // Authorize (allow) all domains to consume the content
     ((HttpServletResponse) servletResponse).addHeader( "Access-Control-Allow-Origin" , "*" );
     ((HttpServletResponse) servletResponse).addHeader( "Access-Control-Allow-Methods" , "GET, OPTIONS, HEAD, PUT, POST" );
     
}

jersey创建一个过滤器,添加以下代码

1
2
3
4
5
6
7
8
9
public class CorsFilter implements ContainerResponseFilter {
 
     @Override
     public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
             throws IOException {
         // 注意,添加的头是小写哦
         responseContext.getHeaders().add( "access-control-allow-origin" , " * " );
     }
}

spring 最简洁,只要在方法上添加注释@CrossOrigin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestController
public class StudentController {
     
     @Autowired
     StudentRepository studentRepository;
 
     @CrossOrigin
     @PostMapping (value= "/students" ,consumes = "application/json" )
     public ResponseEntity<Object> createStudent( @RequestBody Student student) {
         Student savedStudent = studentRepository.save(student);
         URI location = ServletUriComponentsBuilder.fromCurrentRequest().path( "/{id}" )
                 .buildAndExpand(savedStudent.getId()).toUri();
         return ResponseEntity.created(location).build();
     }
}

客户端调用时,添加一个配置参数crossDomain: true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$obj= '{"name":"gt","age":22}' ;
 
$.ajax({
     cache: false ,
     crossDomain: true ,
     url: "http://127.0.0.1:8080/students" ,
     type: "POST" ,
     dataType: "json" ,
     contentType: "application/json" ,
     data:$obj,
     success: function (data) {
        console.log(data);
     }
});
 

转载于:https://www.cnblogs.com/max-hou/p/9543005.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值