Cross-Origin Resource Sharing (CORS) is an HTTP-header-based mechanism that allows a server to specify which origins (domain, scheme, or port) other than its own are permitted to load resources (responses) in a browser.
A cross-origin HTTP request occurs when a client makes a request to a resource located at a different origin (i.e., a different domain, protocol, or port) than the client's own origin.
http://localhost:3000
needs to consume a Spring Boot RESTful web service API hosted at http://host:port/products
.In a Spring Boot application, CORS can be enabled using the @CrossOrigin
annotation at the class or method level in a @RestController
. This allows cross-origin HTTP requests from JavaScript clients.
@CrossOrigin
, specifying the allowed origin(s).@CrossOrigin(origins = "<http://localhost:3000>")
@RestController
public class ProductController {
// REST API methods
}
ProductController
allows cross-origin requests from the React client running on http://localhost:3000
.@CrossOrigin
annotation can be applied at the class level (to allow CORS for all methods in the controller) or at the method level (to allow CORS for specific endpoints).