-2

I'm following this tutorial Spring/Angular

When I run my app I get this error:

Access to XMLHttpRequest at 'http://localhost:8080/api/employees' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I red differents questions 'bout Cross Origin but I don't know exactly where to insert it and what insert on it because in the tutorial never show or use it.

S.A.R.A.
  • 165
  • 1
  • 2
  • 15
  • Add some implementation and it is a duplicate of https://stackoverflow.com/questions/47345282/how-to-add-cors-request-in-header-in-angular-5 – Manit Mar 12 '19 at 08:37

5 Answers5

1
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CORSConfiguration  {

   @SuppressWarnings("deprecation")
    @Bean
        public WebMvcConfigurer corsConfigurer()
        {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "DELETE", "OPTIONS");
                }    
            };
        }
}
0

You can add a proxy.config.json

{
  "/application1/rest": {
    "target": "http://localhost:8060/",
    "secure": false
  },
 "/anotherapp": {
    "target": "http://localhost:8060/",
    "secure": false
  }  
}

Then run using:

directory\angular> ng serve --proxy-config proxy.config.json
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
0

Cross origin has nothing to do with the front-end. All you need to do is allow the URL of the front-end in the back-end. Usually we write a CORS Filter in the back-end and we allow the front-end url in there.

Follow this tutorial CORS with Spring

Dulanjaya Tennekoon
  • 2,408
  • 1
  • 18
  • 31
0

UPDATE

I create a class with the @Configuration annotation in my Server Side (Spring):

package it.si2001.SpringBootJPACRUDExample.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CORSConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedHeaders("*")
                .allowedMethods("GET", "POST", "DELETE");
    }
}//close class
S.A.R.A.
  • 165
  • 1
  • 2
  • 15
0
In Tomcat `web.xml` file set these cors.
`<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>`
Bhagwat Tupe
  • 1,905
  • 1
  • 13
  • 28