Fixing cross-origin issues between local React app and Spring Boot backend

I’m building a React app that talks to a Spring Boot backend. Both are running locally. When I try to send a POST request from React to my Spring Boot API, I get a CORS error. Here’s what I’m doing:

axios.post('http://localhost:8085/api/users/new', { name: 'John' })
  .then(response => console.log('It worked!'))
  .catch(error => console.log('Oops:', error));

The browser throws this error:

OPTIONS http://localhost:8085/api/users/new 401
Preflight request failed: Invalid HTTP status code 401

I’ve set up a CORS filter in my Spring Boot app:

@Component
public class MyCorsFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
    response.setHeader('Access-Control-Max-Age', '3600');
    response.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
    chain.doFilter(req, res);
  }
}

But it’s not working. The preflight request still fails. What am I missing? How can I fix this CORS issue?

It appears the issue might be related to Spring Security. The 401 status code suggests an authentication problem. Have you configured Spring Security to allow unauthenticated access to your endpoints? You might need to add a security configuration class that permits all requests or specifically allows OPTIONS requests. Here’s a snippet that could help:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, '/**').permitAll()
            .anyRequest().authenticated();
    }
}

This configuration allows OPTIONS requests while maintaining security for other endpoints. Remember to adjust it according to your specific security requirements.

hey there, have u tried adding @CrossOrigin to ur controller methods? that worked for me. also, check if ur spring security config is blocking the OPTIONS request. sometimes it gets in the way. might need to allow OPTIONS requests explicitly. good luck!

hmm, interesting problem! have u considered using a proxy in ur React app? it could bypass the CORS issue entirely. What about ur server’s security settings? sometimes firewalls or antivirus can interfere. also, is ur backend definitely running on port 8085? just curious abt these aspects :thinking: