Karthik P
Karthik P

Reputation: 53

Invalid CORS request for post call?

Request URL: ******
Request Method: OPTIONS
Status Code: 403 
Remote Address: ****
Referrer Policy: no-referrer-when-downgrade

For the post call browser showing it as OPTIONS.

The following is the server code:

@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("*");
        }
    };
}

The above code is working fine when I directly call the respective service.

But getting 'invalid cors request' error by calling the service through zuul api gateway.

Any suggestions plz?

Upvotes: 1

Views: 6049

Answers (2)

Karthik P
Karthik P

Reputation: 53

The following solution worked for me.

Add the below code in zuul project:

@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;
}

Adding corsfilter code in all microservices is not required.

Reference: https://stackoverflow.com/a/46277194/4132466

Upvotes: 0

barbariania
barbariania

Reputation: 549

Your browser first checks if POST method is safe to send to the endpoint and if yes then does POST request. You should provide permissions to OPTIONS method and respond it with Allow: GET, HEAD, POST and all should be okay. I faced that problem while working with Python, so it's all about CORS and does not depend on platform.

See more information about it here

Upvotes: 1

Related Questions