AngularJs CrossSite HTTP Requests to SpringBoot RestAPIs

In this tutorial, JavaSampleApproach will show you how to use AngularJs CrossSite HTTP Requests with SpringBoot RestAPIs

Related posts:
Spring Boot – CORS Support using Java Config
Spring CORS example using @CrossOrigin – Spring Boot
AngularJs Table display Data Objects from RestAPIs remote | SpringBoot & BootStrap
AngularJs JsonP request to cross domain | Springboot RestAPI & BootStrap

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.9.0.RELEASE
– AngularJS
– Bootstrap
– Spring Boot – 1.5.7.RELEASE

II. Problems

We have a RestAPI which is hosted at port 9000:

And we use an AngularJs at port 8080 to request above restAPIs:

-> Problem

Angularjs Cross-Site HTTP Requests to RestAPIs SpringBoot - errors

The above Http Request is called cross-site HTTP requests. So we need to configure Access-Control-Allow-Origin in Server at port 9000.

III. Practice

In the tutorial, we build 2 SpringBoot projects as below:

Angularjs Cross-Site HTTP Requests to RestAPIs SpringBoot - 2 projects

Step to do:
– Create Spring Boot projects
– SpringBoot RestAPIs development
– AngularJS and Frontent development
– Run & Check results

1. Create Spring Boot projects

We use SpringToolSuite to create 2 SpringBoot projects {SpringBootAngular, SpringBootRestAPIEnableCrossOrigin}.

SpringBootAngular is used for hosting AngularJs, with 2 dependencies:

Angularjs Cross-Site HTTP Requests to RestAPIs SpringBoot - dependencies

SpringBootRestAPIEnableCrossOrigin is RestAPIs server which has a dependency spring-boot-starter-web:

2. SpringBoot RestAPIs development

We implement a RestAPI in SpringBootRestAPIEnableCrossOrigin project:

2.1 Create data models

– Create Address data model:

– Create Customer data model:

2.2 Implement RestAPIs

2.3 Enable CrossOrigin

We have 2 approach:
– Enable CrossOrigin on a specific request-mapping as below:

– Or use global CORS configuration:

See more at: Spring Boot – CORS

3. AngularJS and Frontent development

We implement AngularJs front-end in SpringBootAngular project.

3.1 Create an html view

3.2 Implement AngularJs

4. Run & Check results

In SpringBootRestAPIEnableCrossOrigin project, open file, configure server.port=9000.

Run the projects with SpringBoot mode.
-> Result:

Angularjs Cross-Site HTTP Requests to RestAPIs SpringBoot - results

If we remove CrossOrigin configuration in SpringBootRestAPIEnableCrossOrigin project, then we will meet the error:

Angularjs Cross-Site HTTP Requests to RestAPIs SpringBoot - errors

IV. Sourcecode


By JavaSampleApproach | October 31, 2017.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *