Reputation: 677
I want to integrate Spring Boot application with Angular application. Both applications are running on a different server. When I will try to hit REST API from the Angular application API hit successfully but I get an error response on UI.
Access to XMLHttpRequest at 'http://localhost:9092/jobs/postal/launch' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I implemented the CORS negotiation on the backend side. So I just want that I am able to hit the backend from UI without any security.
I also read the below article to get an understanding of CORS and CSRF.
https://markitzeroday.com/x-requested-with/cors/2017/06/29/csrf-mitigation-for-ajax-requests.html
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings( CorsRegistry registry) {
registry.addMapping(corsMapping)
.allowedOrigins(allowedOrigins)
.allowedMethods(allowedMethods).allowedHeaders("X-Requested-With");
}
};
}
I just want to know how can I get successfully integrate Spring Boot application with Angular application.
If there is any doc or link that can help me please let me know.
Upvotes: 0
Views: 195
Reputation: 3440
CORS manages the access to the requests originating from the servers other than where backend application is deployed. By-default it is set to only the backend hosting server due to security reasons which means only requests originating from backend hosting server are allowed.
In your case since both backend and UI are running on separate servers you need to add some code changes in backend to allow the UI to access the backend.
You can have a class ResourceApplication.java
as shown below:
@RequestMapping("/")
@CrossOrigin(origins="*", maxAge=3600)
public Message home() {
return new Message("Hello World");
}
The above is taken from this tutorial which is provided by spring.io and is an excellent guide if you are integrating spring-boot with angular. If you scroll down you will find the CORS section.
Upvotes: 2