Issue
My angular web application hosted at http://localhost:4200 makes a request http://localhost:8888/mydomain/path for my spring boot java backend as described below:
Angular frond-end:
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
headers.set('Access-Control-Allow-Origin', '*');
headers.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT');
this.http.get('http://localhost:8888/mydomain/path', { headers: headers })
.subscribe(result => console.log(result));
Searching the internet I found a setting to solve the cors origin problem in the java/spring boot backend
@EnableWebSecurity
@Configuration
public class SecurityConfigurations extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/*").permitAll()
.antMatchers(HttpMethod.POST, "/*").permitAll()
.antMatchers(HttpMethod.PUT, "/*").permitAll()
.antMatchers(HttpMethod.DELETE, "/*").permitAll()
.and().csrf().disable().cors().disable();
}
@Bean
@Qualifier("corsFilter")
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
But the get call is returning the below error. What would be the problem? What am I forgetting to do or doing wrong? ?Thanks a lot
'http://localhost:8888/mydomain/path' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Solution
The solution described by @j1s solved my problem, I just had to make small changes to make it work in my case. I will describe below:
I created the proxy.config.json file in the root of my project
{
"/api": {
"target": "http://localhost:8888",
"pathRewrite": {
"^/api": "/mydomain"
},
"secure": false,
"logLevel": "info"
}
}
I added the configuration in angular.json
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "myapp:build:production"
},
"development": {
"browserTarget": "myapp:build:development",
"proxyConfig": "proxy.config.json"
}
},
"defaultConfiguration": "development"
And finally my call to api needed to be
http://localhost:4200/api/path
That way everything worked perfectly fine. Thanks to @j1s for the solution!
Answered By - araraujo
Answer Checked By - Timothy Miller (JavaFixing Admin)