CORS带cookie跨域问题在Springboot服务端的解法

使用@CrossOrigin注解, 且要指定origins={"host1","host2"...}和allowCredentials = "true"
注解可以放在方法上或controller类上。

而不能直接使用@CrossOrigin,会报

Access to fetch at 'http://xxxx2' from origin 'http://xxxx1' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

也不能设置origins="*", 因为新版的浏览器已经不允许为'Access-Control-Allow-Origin' *了;

也要设置allowCredentials = "true", 不然allowCredentials默认是空字符,浏览器也会报错。

=========================================

官网上的全局设置方式已经失效了:https://spring.io/guides/gs/rest-service-cors/

  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
      }
    };
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章