I struggle around with CORS implementation in my client-server project. CORS means, that calls from other origins (ex. other domain) only allowed if the header contains the CORS value.
So, for example if I host a website on www.domain.com and call an RESTful API on the same domain, everything is fine.
But if I develop an API for an mobile application for example, the mobile does not have the same domain of the API. How could that work together? Does I need everytime the CORS implementation in my service?
The question comes up, since I develop an Angular 2 application, that is running in dev on localhost:4200 and my API runs on localhost:8080 (build with Spring Boot). So the client throws an exception, because it's not the same origin (different port).
The Goal is to host my API on an root server somewhere in the internet, and the client on different webspace provider (because it's just a single Page Application). The api runs with http://1.2.3.4:8080/api/v1 and the client with http://www.example.com:80/myPage
So, does I need to implement Cross-Origin everytime? Or is there another way to realize that?
To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard. For more information on configuring CORS for REST APIs, see Configuring CORS for a REST API resource. For HTTP APIs, see Configuring CORS for an HTTP API.
Due to security concerns, browsers enforce same-origin policy i.e., a script (typically AJAX calls) running in a web page cannot access data from another page residing in a different domain. In some cases, this can be restrictive. CORS (Cross Origin resource sharing) is a W3C specification supported by most modern browsers to specify when it is safe to allow cross origin requests.
In Spring boot, enabling CORS is as easy as adding the @CrossOrigin annotation. This annotation can be added at method level to enable just for that particular request mapping or at the class level to enable for the whole controller.
You could list the domain and port to be allowed by adding an "origins" attribute to the annotation. If it is not specified, all origins are allowed by default (better to avoid this for security reasons).
Below is an example to enable CORS for example.com domain and port 80 at controller level
@CrossOrigin(origins = "http://www.example.com:80")
@RestController
@RequestMapping("/yourmapping")
public class YourController {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With