Spring boot provides a simple way to enable CORS (Cross-Origin Resource Sharing) for your RESTful API.
CORS is a security feature implemented by browsers to prevent malicious websites from making requests to your server. By default, browsers will block requests from different origins, but you can enable CORS to allow requests from specific origins.
Enable CORS
To enable CORS in your Spring Boot application, you can use the @CrossOrigin annotation on your controller class or method. The @CrossOrigin annotation allows you to specify the origins that are allowed to access your API.
@GetMapping("/users") public List<User> getUsers() { // Get users from the database return userRepository.findAll(); } }
You can also enable CORS at the method level.
1 2 3 4 5 6 7 8 9 10
@RestController publicclassUserController {
@GetMapping("/users") @CrossOrigin(origins = "http://localhost:3000") public List<User> getUsers() { // Get users from the database return userRepository.findAll(); } }
Configuration
You can also configure CORS globally for your application by adding a WebMvcConfigurer bean to your application context.