Spring Boot 允许跨域请求、自定义请求头

1:禁止跨域请求
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘xxx’ is therefore not allowed access. The response had HTTP status code 403

2:禁止自定义请求头
Request header field xxx is not allowed by Access-Control-Allow-Headers in preflight response

前后端分离,前端使用Ajax请求一般都会遇着这两配置问题,在Spring Boot中添加如下配置

方式一

@Configuration
public class CorsConf {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

}

方式二

在Application启动类中注册WebMvcConfigurer

@Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };
    }

推荐文章:
【代码规范神器】阿里巴巴Java开发规约IDE插件使用教程(P3C)
Eclipse新建Spring-boot项目,打包部署并输出HelloWord
Java基于Redis实现“附近的人”

猜你喜欢

转载自blog.csdn.net/qq_19260029/article/details/78870330