Spring boot应用程序返回访问“myURL”处的XMLHttpRequest已被CORS策略阻止

2024-04-06

我遇到了这个问题:我在后端使用 Spring Boot 应用程序,在前端使用 Angular 应用程序,问题是当我在后端调用特定的其余 URL 时,该 URL 使用我已作为 Maven 添加到后端的 jar 依赖项系统范围依赖项我收到 cors 错误。所有其他后端 url 都工作正常

这是我如何包含后端的 jar 依赖项:

    <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 调度程序 我在后端做了这个配置

@Component

公共类 CorsFilter 扩展了 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控制器中的注释。 这是文档中的正确配置:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {

            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("*")
                    .allowedHeaders("*");

        }
    };
}

您可以按照自己的方式进行配置。

其次,如果您正在使用SpringSecurity你需要添加.cors()根据您的配置。

Example:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors().and()
                .csrf().disable()
                .authorizeRequests()
                .anyRequest().permitAll()
                .and().httpBasic();
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring boot应用程序返回访问“myURL”处的XMLHttpRequest已被CORS策略阻止 的相关文章

随机推荐