簡體   English   中英

Spring Boot-Cors無法正常工作

[英]Spring boot - cors not work

我的服務器運行在localhost:8080(春季啟動應用程序)和我的前端localhost:3000(角應用程序)。 問題是我想從前端向后端服務器發出請求。 我對cors很熟悉,但是對我來說卻不起作用。 我把它添加到我的服務器:

    @Bean
WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:3000");
        }
    };
}

,但我還是得到了

XMLHttpRequest無法加載http:// localhost:8080 / cars 請求被重定向到“ http:// localhost:8080 / login ”,對於需要預檢的跨源請求,不允許這樣做。

怎么了 ?

根據Spring Framework中的官方博客文章CORS支持 ,如果您啟用了Spring Security ,則必須使用基於過濾器的CORS支持

@Configuration
public class MyConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM