代码之家  ›  专栏  ›  技术社区  ›  Karthik P

post呼叫的CORS请求无效?

  •  0
  • Karthik P  · 技术社区  · 7 年前
    Request URL: ******
    Request Method: OPTIONS
    Status Code: 403 
    Remote Address: ****
    Referrer Policy: no-referrer-when-downgrade
    

    以下是服务器代码:

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                System.out.println("onboard cors");
    
                registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "DELETE", "OPTIONS").allowedOrigins("*").allowedHeaders("*");
            }
        };
    }
    

    当我直接调用相应的服务时,上述代码工作正常。

    但是通过zuul-api网关调用服务,得到“无效cors请求”错误。

    2 回复  |  直到 7 年前
        1
  •  1
  •   barbariania    7 年前

    浏览器首先检查POST方法是否可以安全地发送到端点,如果是,则检查POST请求。您应该为OPTIONS方法提供权限,并用 Allow: GET, HEAD, POST 一切都会好起来的。我在使用Python时遇到了这个问题,所以它完全是关于CORS的,不依赖于平台。

    查看更多信息 here

        2
  •  0
  •   Karthik P    7 年前

    在zuul项目中添加以下代码:

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new org.springframework.web.filter.CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
    

    不需要在所有微服务中添加corsfilter代码。

    参考文献: https://stackoverflow.com/a/46277194/4132466

    推荐文章