-1

Hey I am building a web site in react and I tried fetching data from my backend server built in spring but It won't work. I added CorsConfigurationSource to my security config yet it still doesnt work. My cors security config:

@Bean
CorsConfigurationSource corsConfigurationSource(){
     CorsConfiguration corsConfiguration=new CorsConfiguration();
     corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
     corsConfiguration.setAllowCredentials(true);
     corsConfiguration.setAllowedMethods(Arrays.asList("GET","POST"));
     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
     source.registerCorsConfiguration("/**", corsConfiguration);
     return source;
}

The error that I end up getting: https://i.stack.imgur.com/olGCD.png\ My fetch request (I am posting user credentials):

fetch("http://localhost:8080/login", {
      method: "POST",
      mode:'cors',
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: new URLSearchParams(tempLoginCredentials),
    })
Grimalkin
  • 21
  • 6

2 Answers2

0

I think you need more headers and OPTIONS method.

config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS"));
grekier
  • 2,322
  • 1
  • 16
  • 23
0

CORS in Google Chrome is a bit special on localhost. Read more about it here.

On top of that, PORT does matter in CORS. Note that you enabled port 3000 in your Spring config, but are fetching 8080.

Dorin Botan
  • 1,224
  • 8
  • 19
  • Oh I misunderstood, I thought I was supposed to put in the url of site that is able to share resources, changed that but still nothing thank you though. – Grimalkin May 23 '22 at 10:22