0

Errors when linking backend and frontend of my mini project

Overview:

So basically I have been working on a mini project, which is an e-commerce website which sells medicines. Most recently I was working on the signup page. I have created the frontend for the signup page using React, and backend using RESTApi(Spring Boot). Now the backend works fine, I have included the GET, POST and DELETE methods. I tested it using Postman, and the values can be added. However, the values are replaced as well if I use an already present id(weird as it happens when using the POST Method). But the thing is when I try to link my frontend to backend using axios, it doesn't update, the console logs the following 3 main errors:

Access to XMLHttpRequest at 'http://localhost:8080/post' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
code
: 
"ERR_NETWORK"
config
: 
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
: 
"Network Error"
name
: 
"AxiosError"
request
: 
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
stack
: 
"AxiosError: Network Error\n    at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:47817:14)"
[[Prototype]]
: 
Error
POST http://localhost:8080/post net::ERR_FAILED

I configured CORS by adding the following interface to my project

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 WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000/signup")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*");
    }

} I just want to know if this is the correct method to link. If you want I can add the Frontend, backend(Model class, Controller class) codes. Also I would like to mention that, I'm not a pro and is a complete beginner. Please consider this and any help would be appreciated.

Thank You!!

ChrLipp
  • 15,526
  • 10
  • 75
  • 107

1 Answers1

0

Answer in Kotlin with SPRING_BOOT_VERSION = 3.0.5. Relevant parts for your problem (at least in my opinion) commented. BTW the error method says it all: No 'Access-Control-Allow-Origin' header is present, because you didn't allow it with setAllowedHeaders:

@Bean
fun filterChain(
    http: HttpSecurity
): SecurityFilterChain
{
    // Ignore the configured parts, but your login method should 
    // not have an authentication. I am not sure if this is the
    // case in your application
    http
        .cors(withDefaults())
        .csrf()
            .disable()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().authorizeHttpRequests()
            .requestMatchers(HttpMethod.GET, "/**")
                .permitAll()
            .requestMatchers(HttpMethod.POST, "/api/login")
                .permitAll()
            .anyRequest()
                .authenticated()
        .and().oauth2ResourceServer()
            .jwt()

    return http.build()    }

@Bean
fun corsConfigurationSource(): CorsConfigurationSource
{
    val configuration = CorsConfiguration()
    configuration.allowedOrigins = listOf("http://localhost:3000")
    configuration.allowedMethods = listOf("*")
    // set Headers for CORS request, see linked answers
    configuration.allowedHeaders = listOf(
        "Access-Control-Allow-Origin", "Authorization", "Cache-Control", "Content-Type")
    configuration.exposedHeaders = listOf("Authorization")

    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", configuration)

    return source
}

See https://stackoverflow.com/a/43559288/734687 and Axios get access to response header fields

So to summarize (with Java), try to add

    configuration.setAllowedHeaders(ImmutableList.of("Access-Control-Allow-Origin", "Authorization", "Cache-Control", "Content-Type"));
ChrLipp
  • 15,526
  • 10
  • 75
  • 107
  • where should I add the second snippet? – Simon Riley May 28 '23 at 10:13
  • Configure CORS this way: https://docs.spring.io/spring-security/reference/servlet/integrations/cors.html – ChrLipp May 28 '23 at 11:03
  • Or when you stick to your config, see 3.1 of https://howtodoinjava.com/spring-boot2/spring-cors-configuration/ – ChrLipp May 28 '23 at 11:06
  • I got it I created a class in my main package, the one that I gave in my question. It works now. My page fetches data from backend now. Now I have another issue, I guess I'll post it as another question. Thank you for your time @ChrLipp. God Bless You! – Simon Riley May 28 '23 at 13:25