Spring Boot Rest API @CrossOrigin不起作用

时间:2019-01-10 12:00:57

标签: rest spring-boot

我知道这个问题已经问过了,但是我遇到了同样的问题,没有找到任何解决办法

Spring Boot,我有Rest API,并添加了跨域注释

@CrossOrigin(origins = "*", allowedHeaders = "*")

但是它仍然显示一个错误

Access to XMLHttpRequest at 'http://localhost:8080/API/findUser' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false}

我也尝试过

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

但不起作用

1 个答案:

答案 0 :(得分:0)

以防万一有人在谷歌搜索后发现了这个问题,这可能会解决问题。 如果您使用的是 Spring 安全性。您也应该在那里启用 cors() 。像这样设置您的 WebSecurityConfigurerAdapter:

       public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http
                .cors() //<-- Enables CORS
                .and()
                    .antMatcher("/api/**")
                    .authorizeRequests()
                    .anyRequest()
                    .hasRole("admin")
                    .and()
                        .oauth2ResourceServer()
                        .jwt()
                        .jwtAuthenticationConverter(new CustomJwtAuthenticationConverter());
        }

    }