2
votes

I have call to Spring REST web service from Angular http service. I am calling get method. I am getting following exception.

Failed to load http://127.0.0.1:8080/SpringRestExample/rest/emp/dummy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I added header on client and server side as below but still error exist.

Client Side:

let headers= new Headers();
 headers.append('Access-Control-Allow-Headers', 'Content-Type,application/json');
 headers.append('Access-Control-Allow-Methods', 'GET');
 headers.append('Access-Control-Allow-Origin', 'http://localhost:4200');
 let options = new RequestOptions({ headers: headers });
this.http.get("http://127.0.0.1:8080/SpringRestExample/rest/emp/dummy",options).subscribe(data => {
  console.log(data);

Server Side

httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,'application/json'");

Anyone know solution?

1
Is server runing on your local host or any other system?sridhar..
have you try with httpResponse.setHeader("Access-Control-Allow-Origin", "*");? If it works, the problem may be your domain of local serverNhon Dinh
Client Side - don't use response headers in a request - besides it making no sense, it guarantees a preflight OPTIONS request which I doubt your server even handles, as you clearly haven't understood how CORS worksJaromanda X

1 Answers

0
votes

Remove the client side headers and add

httpResponse.setHeader("Access-Control-Allow-Origin", "*");

to your server side code.

I have a spring boot configuration for CORS and works fine :

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "OPTIONS", "GET", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true).maxAge(3600);
    }
}