Levi
Levi

Reputation: 83

Spring Boot, Angular2, Cross-origin

I have a web-server in Spring Boot. I can send HTTP requests to it and get answers from tools like Send HTTP. I also have a web site based on Angular2 whoich works too. Part of the functionality must include HTTP requests from the Angular2 running in Chrome to the Spring Boot server. Every time I do it I have an error in Chrome console:

XMLHttpRequest cannot load 'URL Server'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'URL Client' is therefore not allowed access.

I put into Spring server @CrossOrigin in all places where it makes sense: before @Controller, @RequestMapping, @GetMapping, but it did not help. What I am missing and how to overcome? Great thanks, a bit desperate, Levi

Upvotes: 0

Views: 1509

Answers (4)

Milan Hlinák
Milan Hlinák

Reputation: 4430

You need setup a proxy to backend as is described here.

1) Create file proxy.conf.json (next to package.json) with the content

{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

2) Edit start script in package.json

"start": "ng serve --proxy-config proxy.conf.json"

3) Run with

npm start

Upvotes: 0

Yassine Chargui
Yassine Chargui

Reputation: 13

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

try this it works for me !

Upvotes: 1

Barath
Barath

Reputation: 5283

Try like below:

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("<<MAPPING>>").allowedOrigins("<<ORIGINS>>");
            }
        };
    }

Please go through below tutorial and try with alternate option if still not working :

https://spring.io/guides/gs/rest-service-cors/

Update 1:

As updated by @Levi

    import org.springframework.web.cors.CorsConfiguration; //+ more public class RestConfiguration { 

    @Bean public CorsFilter corsFilter() { 

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); 
    config.setAllowCredentials(true);
     config.addAllowedOrigin("*"); 
    config.addAllowedHeader("*"); 
    config.addAllowedMethod("*"); 
    source.registerCorsConfiguration("/**", config);
     return new CorsFilter(source); } 

}

Upvotes: 0

Saket Puranik
Saket Puranik

Reputation: 117

You need to add CQRSFilter for your application and set that CORSFilter in your spring boot configuration class.

What you have to do is

1> Create your own CQRSFilter that implements Filter

2>You should add code as below in your filter

@Component
public class CORSFilter implements Filter{
static Logger logger = LoggerFactory.getLogger(CORSFilter.class);

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    chain.doFilter(request, response);
}

public void destroy() {}
}

3> Place your filter in spring configuration file

@EnableWebMvcSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {



@Override
protected void configure(HttpSecurity http) throws Exception {
  http
      .addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)

  }
 }

Upvotes: 0

Related Questions