Mr.DevEng
Mr.DevEng

Reputation: 2421

Spring Boot microservice response issue with Angular 2 http call

I am trying to call a GET request from my Angular 2 front-end app to a Spring Boot REST microservice, But when I calling, I am getting error like:

No Access-Control-Allow-Origin header is present on the requested resource

Here is my controller actions:

@RequestMapping(value = "/checkUsers", method = RequestMethod.POST)
public String checkLogin(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    List<Users> useObj = (List<Users>) userRepo.findAll();
    return(mapper.writeValueAsString(useObj));
}

And when I am running my Angular, I am getting the above error. I added its screenshot

enter image description here

Is this from an Angular problem or from a Spring Boot microservice response problem?

Upvotes: 0

Views: 596

Answers (4)

brax7
brax7

Reputation: 182

Creating a Spring Boot Component class which implements javax.servlet.Filter interface and adding the required header solved a similar issue of mine.

@Component
public class YourAppCorsFilter implements Filter{

@Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(req, res);
    }
}

Let me know if you still face issues after adding this to your micro-service.

Upvotes: 0

Satish Kr
Satish Kr

Reputation: 628

In you Application.java add a bean

 @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    return bean;
  }

It is global and it will work for every controller of your project.

Upvotes: 0

hiper2d
hiper2d

Reputation: 2884

The accepted answer is good since it provides a working solution but it also forces you to hardcode client's URL on the server side in every controller. You can set up a global CORS configuration instead. If your web configuration extends the WebMvcConfigurereAdapter class you can simply override the addCorsMappings method. The following example enables CORS for the whole application:

@Configuration
public class WebConfig extends WebMvcConfigurereAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

Read more about CORS support in Spring here

Upvotes: 0

Pavle Eftimovski
Pavle Eftimovski

Reputation: 124

Since they are running on different ports, you have to allow Cross-origin resource sharing (CORS) on server side. In spring boot you can do that by adding @CrossOrigin annotation to the handler method:

@CrossOrigin(origins = "http://localhost:4200")

It is also possible to add this annotation at controller class level as well, in order to enable CORS on all handler methods of that class.

Upvotes: 2

Related Questions