Doni Doni - 1 month ago 18
AngularJS Question

CORS not allowed use a POST method

My application is divied by two servers gulp and tomcat.
On front is AngularJS on back Spring boot.
Gulp working on port 3000 and tomcat on 8080.

I send request from localhost:3000 to my api (localhost:8080/api/register) using POST method and my spring response HTTP Status code 403.


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:3000' is therefore not allowed
access. The response had HTTP status code 403.


I'm tried add to controllers Annotation @CrossOrigin but this didn't help.

Also, I added to my WebConfig the following code:

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000").allowedMethods("OPTIONS","POST", "GET", "PUT", "DELETE");
}
};
}


The above code help but only for GET request.
Any idea why it's doesn't work ?

Answer

I solved the problem by adding the following code to the configuration of tomcat.

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter