配置Spring Boot 跨域后PUT,DELETE方法出現403Forbidden


配置類

@Configuration
public class CorsConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

前端請求

錯誤原因:SpringBoot默認跨域方法只支持HEAD,GET,POST

配置類修改后

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

附相關SpringBoot部分源碼

//package org.springframework.web.cors.CorsConfiguration
/** Wildcard representing <em>all</em> origins, methods, or headers. */ public static final String ALL = "*"; private static final List<HttpMethod> DEFAULT_METHODS = Collections.unmodifiableList( Arrays.asList(HttpMethod.GET, HttpMethod.HEAD)); private static final List<String> DEFAULT_PERMIT_METHODS = Collections.unmodifiableList( Arrays.asList(HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name())); private static final List<String> DEFAULT_PERMIT_ALL = Collections.unmodifiableList( Collections.singletonList(ALL));


public
CorsConfiguration applyPermitDefaultValues() { if (this.allowedOrigins == null) { this.allowedOrigins = DEFAULT_PERMIT_ALL; } if (this.allowedMethods == null) { this.allowedMethods = DEFAULT_PERMIT_METHODS; this.resolvedMethods = DEFAULT_PERMIT_METHODS .stream().map(HttpMethod::resolve).collect(Collectors.toList()); } if (this.allowedHeaders == null) { this.allowedHeaders = DEFAULT_PERMIT_ALL; } if (this.maxAge == null) { this.maxAge = 1800L; } return this; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM