How to Fix CORS Error in Spring Boot: Simple Steps
CORS error in Spring Boot, you need to allow cross-origin requests by configuring @CrossOrigin annotations or a global CorsConfiguration. This tells your backend which external domains can access its resources, preventing the browser from blocking requests.Why This Happens
CORS errors happen because browsers block web pages from making requests to a different domain than the one that served the page. This is a security feature called the Same-Origin Policy. If your Spring Boot backend does not explicitly allow requests from other origins, the browser will stop the request and show a CORS error.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ApiController { @GetMapping("/data") public String getData() { return "Hello from backend"; } }
The Fix
You fix CORS errors by telling Spring Boot which origins are allowed to access your backend. You can do this by adding @CrossOrigin on your controller or method, or by defining a global CORS configuration bean. This adds the necessary headers so the browser allows the request.
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin(origins = "http://localhost:3000") public class ApiController { @GetMapping("/data") public String getData() { return "Hello from backend"; } }
Prevention
To avoid CORS errors in the future, always configure your backend to explicitly allow trusted origins. Use @CrossOrigin for simple cases or a global CorsConfiguration bean for complex setups. Avoid using * (allow all) in production for security reasons. Test your API with different clients early to catch CORS issues.
Related Errors
Other errors related to CORS include:
- Preflight request failures: When the browser sends an OPTIONS request before the actual request and the server does not respond correctly.
- Missing headers: If
Access-Control-Allow-MethodsorAccess-Control-Allow-Headersare not set properly. - Credentials issues: When cookies or authorization headers are sent but
Access-Control-Allow-Credentialsis not enabled.