CORS和错误以及Access-Control-Allow-Origin标头的问题 [英] Issue with CORS and error and Access-Control-Allow-Origin header

查看:154
本文介绍了CORS和错误以及Access-Control-Allow-Origin标头的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在我的项目中禁用CORS.我将自定义过滤器和Spring Security Config用于CORS配置.我已经看到了一个很好的答案:可以在Spring中完全禁用CORS支持吗?

Hi I cant disable CORS in my project. I use a custom filter and Spring Security Config for the CORS configuration. I have seen this excellent answer: Can you completely disable CORS support in Spring?

但是当我尝试了以下实现时,我仍然收到CORS错误:

but when I have tried the below implementation I still get the CORS error:

CORS配置:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class CorsFilter @Autowired
constructor() : CorsFilter(configSrc()) {
    companion object {

    private fun configSrc(): UrlBasedCorsConfigurationSource {
        val config = CorsConfiguration()
        config.allowCredentials = true
        config.addAllowedOrigin("http://127.0.0.1:3000")
        config.addAllowedHeader("*")
        config.addAllowedMethod("*")
        val src = UrlBasedCorsConfigurationSource()
        src.registerCorsConfiguration("/**", config)
        return src
    }
}

}

我也尝试将允许的原点设置为如下所示,但没有结果:

Ive also tried setting the allowed origin to be like below with no results:

config.addAllowedOrigin("http://127.0.0.1:3000")

这些是来自进行中的OPTIONS请求的Response标头:

These are the Response headers from the proceeding OPTIONS request:

这是我得到的确切错误:

This is the exact error I am getting:

您能否指出任何其他想法,或者为什么会这样呢?我以为这是一个容易解决的问题,但最终却浪费了我很多时间.

Could you please point out any additional ideas or why this might be happening? I thought that this would be a simple to fix issue but it has ended up consuming quite a lot of my time.

谢谢

推荐答案

您可以尝试通过以下方式在应用程序类中添加CORS映射:

You can try adding CORS mapping in the application class in this way:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/v1/**")
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(true)
                .maxAge(3600);
            }
        };
    }

https://spring.io/guides/gs/rest-service- cors/

这篇关于CORS和错误以及Access-Control-Allow-Origin标头的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆