Ava89
April 27, 2025, 10:54am
1
I’m stuck with a CORS problem when trying to connect my React app to a Spring Boot backend. Both are running locally. Here’s what’s happening:
axios.post('http://localhost:8085/api/users/new', {userData})
.then(res => console.log('All good!'))
.catch(err => console.error(err));
But I keep getting this error:
OPTIONS http://localhost:8085/api/users/new 401
Preflight request failed: Invalid HTTP status code 401
I’ve tried setting up a CORS filter in Spring Boot:
@Component
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.maxAge(3600);
}
}
But it’s not working. The API endpoint looks like this:
@PostMapping("/new")
public ResponseEntity<?> addUser(@RequestBody UserDto userDto) {
// Logic here
}
I’ve double-checked the URLs and they’re correct. What am I missing? Any ideas on how to fix this CORS issue?
hmm, have u considered using @CrossOrigin annotation on ur controller? it’s a quick fix:
@RestController
@CrossOrigin (origins = “http://localhost:3000 ”)
public class UserController {
// ur methods here
}
tho it might not be the best for production. what kinda authentication r u using? that 401 is sus…
The 401 status code suggests an authentication problem rather than a straightforward CORS issue. Your CORS configuration looks correct, but it seems the request is being intercepted by Spring Security before reaching your CORS filter.
Try adding this to your security configuration:
@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()
.and()
.httpBasic();
}
}
This allows OPTIONS requests to pass through without authentication. If you’re not using Spring Security, check if there’s any other filter or interceptor causing the 401 error. Also, ensure your backend is actually running on port 8085 as specified in your React code.
hav u tried using a proxy in ur React app? sometimes that helps bypass CORS. in package.json, add:
“proxy”: “http://localhost:8085 ”
then in ur axios call, just use the relative path:
axios.post(‘/api/users/new’, {userData})
might solve it without changin backend stuff