【问题标题】:CORS issue when accessing the same resource with GET and POST使用 GET 和 POST 访问同一资源时出现 CORS 问题
【发布时间】:2020-02-20 18:05:37
【问题描述】:

当使用 GET 访问资源时,我会在服务器上检查用户是否已登录,并将他重定向到不同服务器上的 SSO 登录页面,但在同一域中。这工作得很好。 当用户发布相同的资源时,我尝试执行相同的操作,但现在浏览器显示“请求的资源上不存在‘Access-Control-Allow-Origin’标头。”。 为什么它适用于 GET 而不适用于 POST?

【问题讨论】:

    标签: java spring-mvc post get cors


    【解决方案1】:

    您需要验证您的后端是否已经为 GET、POST 和其他 HTTP 方法配置了 cors。

    我的 spring config 类有这样的配置:

    例如:

       @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        corsConfiguration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        corsConfiguration.setExposedHeaders(Arrays.asList("x-auth-token"));
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
    
        return source;
    }
    

    【讨论】:

      【解决方案2】:

      我在使用 Spring Boot 和 Restful API 时遇到了类似的问题。

      您必须在标题中包含 Access-Control-Allow-Origin,例如:

      @RequestMapping("responseHeader")   
      public @ResponseBody ResponseEntity<String> responseHeaderExample(){
              HttpHeaders responseHeaders = new HttpHeaders();
              responseHeaders.set("Access-Control-Allow-Origin", "*");
      
              String _response = "Hello Word";
      
      return new ResponseEntity<String>(_response, HttpStatus.OK).ok().headers(responseHeaders).body(_response);
      }
      

      【讨论】:

        猜你喜欢
        • 2019-06-28
        • 1970-01-01
        • 2021-04-22
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-08
        • 1970-01-01
        相关资源
        最近更新 更多