春季启动应用在"myURL"处返回对XMLHttpRequest的访问.已被CORS政策封锁 [英] Spring boot app return Access to XMLHttpRequest at "myURL" has been blocked by CORS policy
问题描述
我遇到了这个问题:我在后端使用spring boot应用程序,在前端使用angular应用程序,问题是当我在后端调用使用添加到jar的jar依赖项的特定rest url时后端作为Maven系统范围的依赖关系,我得到了一个cors错误.所有其他后端网址都可以正常工作
i'm stuck with this issue: i use a spring boot app in backend and angular app for the front, the issue is when i call a specific rest url in the backend that uses a jar dependency that i have added to the backend as maven system scope dependency i get a cors error. All other backend urls are working fine
这是我为后端添加jar依赖项的方式:
here is how i included the jar dependency for the backend:
<dependency>
<groupId>com.ex</groupId>
<artifactId>lib</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/Utils.jar</systemPath>
</dependency>
还请注意,我在前端和后端之间使用了Zuul调度程序而且我在后端做了这个配置
note also that i'm using a Zuul dispatcher between the front and the backend and that i did this config in the backend
@Component
公共类CorsFilter扩展了OncePerRequestFilter {
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token, Content-Range, Content-Disposition, Content-Description, GAuth");
response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
非常感谢您的任何帮助
推荐答案
首先,您需要在控制器中添加 @CrossOrigin
批注.比这里是文档中正确的配置:
Firstly, you need add @CrossOrigin
annotation in your controller.
Than here is correct configuration from documentation:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
};
}
您可以按照自己的方式进行配置.
You can configure it your own way.
第二,如果您使用的是 SpringSecurity
,则需要在配置中添加 .cors()
.
Secondly, if you are using SpringSecurity
you need add .cors()
to your configuration.
示例:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.authorizeRequests()
.anyRequest().permitAll()
.and().httpBasic();
}
这篇关于春季启动应用在"myURL"处返回对XMLHttpRequest的访问.已被CORS政策封锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!