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.
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");
}
};
}
}
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
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
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
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>`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.