0

Even though I used @CrossOrigin annotation this error still appears. Spring boot app is running on 8080 port and react app is running on 3000 port.

image of backend controller

Error:

Error in console

If further information is needed, please let me know.

2 Answers2

1

I assume you are using spring security. @CrossOrigin filter might have a lower precedence over spring security filters. Try to configure CORS using spring security.

sanurah
  • 976
  • 1
  • 6
  • 16
1

I resolved my issue with the answer given by @Sanura. Then blockage done by the CORS is avoided.

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/auth/login", "/auth/register","/post/savePost", "/post/**", "/post/getPost/{id}","/post/updatePost/{id}")
                .permitAll().anyRequest().authenticated()
                .and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }

I added the routes to the configure method as above.

The below mentioning code sample also can be used instead of this.

package com.myapp.springboot.configs;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebMvcConfiguration implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*").
            allowedOrigins("*").
            allowedMethods("*").
            allowedHeaders("*").
            allowCredentials(true);
        }
    }

Thank you for your support.