[英]How does Cross Origin works between Spring Boot and Angular Cli?
I'm following this tutorial Spring/Angular我正在关注本教程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. CORS 策略已阻止在 ' http://localhost:8080/api/employees ' 从源 ' http://localhost:4200 ' 访问 XMLHttpRequest :请求的资源。
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.我提出了关于 Cross Origin 的不同问题,但我不知道在哪里插入它以及在它上面插入什么,因为在教程中从未显示或使用它。
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你可以添加一个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.
您需要做的就是在后端允许前端的 URL。 Usually we write a CORS Filter in the back-end and we allow the front-end url in there.
通常我们在后端写一个 CORS 过滤器,我们允许前端 url 在那里。
Follow this tutorial CORS with Spring按照本教程使用 Spring 进行 CORS
UPDATE更新
I create a class with the @Configuration annotation in my Server Side (Spring):我在服务器端 (Spring) 中创建了一个带有 @Configuration 注释的类:
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>`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.