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),
})
CodePudding user response:
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.
CodePudding user response:
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"));