Access to XMLHttpRequest at ‘http://localhost:8080/api/submitForm’ from origin ‘http://localhost:5173’ 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.
Here’s my CORS configuration class in my Spring Boot backend:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
And here’s how I’m making the API call in my React component:
import axios from 'axios';
const baseURL = "http://localhost:8080/api";
const sendDataToBackend = (data) => {
axios
.post(`${baseURL}/submitForm`, data)
.then((response) => {
console.log("Data sent successfully", response.data);
// Additional logic
})
.catch((error) => {
console.error("Error sending data to the backend", error);
// Error handling logic
});
};
I’ve configured my backend to allow all origins and methods, including POST, which should theoretically resolve the CORS issue. However, I’m still encountering the error. Any insights on how to resolve this would be greatly appreciated. Thank you!
I updated the CORS configuration in my Spring Boot backend to allow all origins and methods, including POST requests. I expected this configuration to resolve the CORS issue and allow my React application to successfully send data to the backend API without encountering the CORS error. However, despite making these changes, the CORS error persisted, and I’m still unable to send data to the backend.