CORS stands for Cross-Origin Resource Sharing, a security feature that is implemented by web browsers to protect users from malicious websites that try to access data on another domain without permission. It occurs when an application attempts to make a request to a different domain than the one that served the application.
In an Angular or client application, while handling requests and responses through backend APIs using HttpClient, sometimes we face CORS issues, as shown below:
@CrossOrigin in Spring Boot
The @CrossOrigin annotation is used to permit the request on specific handler classes or handler methods with the help of appropriate handler mapping.
In the above application, we are trying to delete the record that is using backed services developed in Spring Boot. We can overcome this issue with the help of the @CrossOrigin annotation. For this, go to the Controller class and add the @CrossOrigin annotation as follows:
@RestController
@CrossOrigin(
origins = "http://localhost:4200",
methods = {
RequestMethod.GET,
RequestMethod.POST,
RequestMethod.PUT,
RequestMethod.DELETE
}
)
public class EmployeeController {
@Autowired
private EmployeeServiceImpl employeeServiceImpl;
.
.
.
}
The above configuration will handle the CORS issue for HTTP methods of type GET, POST, PUT, and DELETE.