CORS Blocking Requests from Client App Android — Backend Does Not Process POST /notification
Description
When making a request to the /notification
endpoint from a client application (in development), the backend does not process the request.
No logs are generated on the server, and the request is blocked before reaching the controller.
The browser or client logs show a CORS error similar to:
Access to fetch at 'http://
Steps to Reproduce
- Run the backend locally (Spring Boot).
- Attempt a
POST /notification
from the client app android or frontend hosted on a different origin. - Observe the CORS error in the browser or client logs.
- Notice that the backend does not receive or log the request.
Expected Behavior
The backend should respond to the preflight (OPTIONS
) request with appropriate CORS headers, allowing the browser or client to send the actual POST request.
Possible Cause
CORS is not configured on the backend, blocking cross-origin requests.
Option 1 - Global CORS Configuration via Java Code
Add a global CORS configuration class such as:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000", "http://myapp.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}
}
Option 2 - Configure via application.properties
spring.web.cors.allowed-origin-patterns= spring.web.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS spring.web.cors.allowed-headers= spring.web.cors.allow-credentials=true