An Angular app is served by a different host than a Spring Boot API, so reaching for data via REST API will result in the following error:
"Failed to load http://localhost:8080/api: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access."
Read this post to learn how to configure Cross-origin resource sharing (CORS) to enable the cross-domain communication on a development environment.
For security reasons, browsers don’t allow calls to resources residing outside the current origin. To specify what kind of cross-domain requests are authorised in our app, we are going to configure
Allow Angular to consume data fetched by Spring Boot
In this example we are working on a project that is built with Maven into a single application with frontend powered by
Angular and backend run with
Spring Boot. Therefore, we require
CORS only on the development environment, to enable working on an Angular app without the need of rebuilding the whole project.
You can find the spring-boot-angular-scaffolding project repository on GitHub.
DevCorsConfiguration class to your
This configuration enables
CORS requests from any origin to the
api/ endpoint in the application. You can narrow the access by using the
allowCredentials methods – check out the examples in this spring.io blog post.
Declare the active profile of your application
Spring provides a way to configure an application accordingly to various environments – it picks up the application configuration based on the active profile.
DevCorsConfiguration class uses
@Profile annotation to load its configuration only on a development environment. We will specify the active profile in the
The work done in this post is contained in the commit 405a4aa5bae96105af5581551c1e6341c3b7acbf.
Run the backend and frontend modules separately, then open your browser on, you should see this Angular start screen, without any errors in the console:
Thanks to the Stormbreaker’s comment I realised I should edit the post to add the following.
You didn’t specify OPTIONS in the allowed methods list
To obtain the communication options available for the target resource, a preflight request with the Preflighted requests in CORS and Functional overview chapters in the MDN web docs about CORS. Make sure that the method is allowed:method is sent. You can read about the details in the
I missed that in the original version of my project, you can find the update in the 817bbe2acea969b1f686f2d721490d75ffef1631 commit.
|Be aware, that not all requests trigger a CORS preflight. You can read about it in the Simple requests chapter in the MDN web docs.|
You want to authorise users
When your project uses authentication and authorisation mechanisms, like Json Web Token standard, you should configure it to process authorisation header. Addto the method like in the example below (line 17):